访问Object类型中的方法

本文关键字:方法 类型 Object 访问 | 更新日期: 2023-09-27 18:05:23

我正试图弄清楚如何在csharp中做以下事情(这是在我的脑海中键入的,所以它可能不是100%准确,但它应该得到重点),但我真的不确定如何。

class Test
{
  private __construct() {}
  public static function GetInstance($name)
  {
      if (file_exists($name . ".php"))
      {
            return new $name();
      }
      else
      {
            return null;
      }
  }
}

我知道如何根据输入返回我想要的对象,但是我必须返回一个object,因为我不确定调用者将请求哪个对象。但是,当我不知道如何访问返回对象中的方法时。

访问Object类型中的方法

假设我正确理解了您的伪代码,您将不得不将结果对象强制转换为您期望的类型,以便您可以访问该类型的公共方法:

Foo myFoo = (Foo) Test.GetInstance("Foo");
string bar = myFoo.Bar();

也检查Activator.CreateInstance()方法,它基本上做你的GetInstance方法想做的。

如果我正确地解释你的问题,我认为你想按类型名称创建一个对象。有很多方法可以做到这一点。这是一个例子:

public static class Test
{
    public object CreateInstance(string typeName)
    { 
        Type type = Type.GetType(typeName);
        return Activator.CreateInstance(type);
    }
}

这里假设typeName是包含命名空间的完整类型名,并且该类型有一个默认(无参数)构造函数。否则该方法将失败。例如,您必须将您的类型强制转换为User,以便访问User类型中的方法。

User user = (User)Test.CreateInstance("Some.Namespace.User");
// Now methods and propertes are available in user
Console.WriteLine("User name: "+user.Name);

希望这个帖子也有帮助。下面是一些更多的反射示例。

// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));

// create instance of DateTime, use constructor with parameters (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),
                                                       new object[] { 2008, 7, 4 });