前提・実現したいこと
指定したクラスをStackに入れました。
メソッド内でそのStackを受け取り、Stackの各要素のクラスのプロパティにアクセスしたいのですが、
エラーになります(下記コードのコメント部分です)。
メソッド内で、Stackの各要素のクラスのプロパティにアクセスすることが可能であれば、
下記コードの修正方法を教えていただきたいです。
また、不可能であった場合、下記コードの意図したいことに近い形のものを教えていただきたいです。
※やりたいことを質問用に簡素化したのがTestクラスです。
Stackの要素に直接stringを入れる仕様は考えていません。
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; class Test{ string s =""; public Test(string b){ s = b; } } public class Sample : MonoBehaviour { void Start () { Stack<Test> tests = new Stack<Test>(); tests.Push (new Test ("1")); tests.Push (new Test ("2")); tests.Push (new Test ("3")); string content = getReverseTest<Test> (tests); Debug.Log (content); } string getReverseTest<T>(Stack<T> tests){ string content = ""; for (int i = 0; i < tests.Count; i++) { //.sにアクセスしたいけど、認識してくれない。 content += tests.ElementAt (tests.Count - i - 1).s; } return content; } }
###追記。
sをpublicにしてみましたが、エラーメッセージが表示されます。
class Test{ public string s =""; public Test(string b){ s = b; } }
Assets/Sample.cs(33,53): error CS1061: Type `T' does not contain a definition for `s' and no extension method `s' of type `T' could be found. Are you missing an assembly reference?
###追記②
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; class Test{ public string s =""; public Test(string b){ s = b; } } public class Sample : MonoBehaviour { void Start () { Stack<Test> tests = new Stack<Test>(); tests.Push (new Test ("1")); tests.Push (new Test ("2")); tests.Push (new Test ("3")); string content = getReverseTest<Test> (tests); Debug.Log (content); } string getReverseTest<Test>(Stack<Test> tests){ string content = ""; for (int i = 0; i < tests.Count; i++) { content += tests.ElementAt (tests.Count - i - 1).s; } return content; } }
error CS1061: Type `Test' does not contain a definition for `s' and no extension method `s' of type `Test' could be found. Are you missing an assembly reference?
ちなみに下記は通ります。
string ss = new Test ("1").s; Debug.Log (ss); //1
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/02/17 10:32
2018/02/17 11:35
2018/02/17 11:47
2018/02/17 13:27