0

抽象クラスを返すメソッドがあります

    public static object CurrentInfo()
    {
        // some code here

        return new
        {
            URL = "www.mydomain.com",
            User = "Jack",
            Age = 20
        };
     }

メソッドを使用すると、抽象クラスの結果が得られるので、それをオブジェクト(またはvar ) 型に取り込みます。

 object obj = MyClass.CurrentInfo();
 //var obj = MyClass.CurrentInfo(); // I also tried that

objオブジェクトからプロパティURLAge、およびUserにアクセスできません。以下を試してみると、エラーが発生します。

 string myUrl = obj.URL // the same form Age and User

私はそれをキャストする必要がありますか?でも何に…?新しいSTRUCTを作成する方法を除外したいと思います。

4

3 に答える 3

5

これらのプロパティを使用してクラスを作成し、それらに適切にアクセスできるようにします。戻りオブジェクトは、匿名クラスではなく、厳密に型指定されたクラスにすることができます。このようにして、オブジェクトのプロパティにアクセスできます。

そのような

public class Info
{
   public string URL {get; set;}
   public string User {get; set;}
   public int Age {get; set;}
}

public static Info CurrentInfo()
    {
        // some code here

        return new Info()
        {
            URL = "www.mydomain.com",
            User = "Jack",
            Age = 20
        };
     }
于 2013-11-01T14:43:52.407 に答える