开发者

Access to methods in Object type

开发者 https://www.devze.com 2023-03-27 18:25 出处:网络
I\'m trying to figure out how to do something like the following (that was typed off the top of my head so it might not be 100% accurate, but i开发者_开发百科t should get the point across) in csharp,

I'm trying to figure out how to do something like the following (that was typed off the top of my head so it might not be 100% accurate, but i开发者_开发百科t should get the point across) in csharp, but I'm not really sure how.

class Test
{
  private __construct() {}

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

I know how to get the object I want back based on the input, but I have to return an Object, because I'm not sure which one the caller will request. However, when I have no idea how to get access to the methods in the returned Object.


Assuming I understand your pseudo code correctly you will have to cast the resulting object to the type that you are expecting so you can access the public methods of that type:

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

Also check the Activator.CreateInstance() method which basically does what your GetInstance method wants to do.


If I interpret your question correctly I think you want to create an object by type name. There are a number of ways to do this. This is one example:

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

This assumes the typeName is a full type name including namespace, and that this type has a default (no argument) constructor. Otherwise the method will fail. Use for example like this (you have to cast to User your type in order to access the methods in the User type.

User user = (User)Test.CreateInstance("Some.Namespace.User");

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


Hope this thread also helps. Here is some more reflection examples.

// 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 });
0

精彩评论

暂无评论...
验证码 换一张
取 消