簡體   English   中英

獲取對類的引用並僅從字符串值執行靜態方法?

[英]Get reference to a class and execute static method from only a string value?

如何獲取帶字符串的靜態類的實例?

例:

class Apple : IFruit
{
    public static Apple GetInstance() { ... }
    private Apple() { }

    // other stuff
}

class Banana : IFruit
{
    public static Banana GetInstance() { ... }
    private Banana() { }

    // other stuff
}

// Elsewhere in the code...
string fruitIWant = "Apple";
IFruit myFruitInstance = [What goes here using "fruitIWant"?].GetInstance();

這是一個完整的例子。 只需傳入要加載的類型的名稱以及要調用的方法的名稱:

namespace Test
{

    class Program
    {
        const string format = @"hh\:mm\:ss\,fff";
        static void Main(string[] args)
        {
            Console.WriteLine(Invoke("Test.Apple", "GetInstance"));
            Console.WriteLine(Invoke("Test.Banana", "GetInstance"));
        }
        public static object Invoke(string type, string method)
        {
            Type t = Type.GetType(type);
            object o = t.InvokeMember(method, BindingFlags.InvokeMethod, null, t, new object[0]);
            return o;
        }

        }
        class Apple 
        {
            public static Apple GetInstance() { return new Apple(); }
            private Apple() { }

            // other stuff
        }

        class Banana
        {
            public static Banana GetInstance() { return new Banana(); }
            private Banana() { }

            // other stuff
        }

}
Type appleType = Type.GetType("Apple");
MethodInfo methodInfo = appleType.GetMethod(
                            "GetInstance",
                            BindingFlags.Public | BindingFlags.Static
                        );
object appleInstance = methodInfo.Invoke(null, null);

請注意,在Type.GetType您需要使用程序集限定名稱

你喜歡這樣:

string fruitIWant = "ApplicationName.Apple";

IFruit a = Type.GetType(fruitIWant).GetMethod("GetInstance").Invoke(null, null) as IFruit;

對於ApplicationName您可以替換聲明類的名稱空間。

(經過測試和工作。)

好的,可能是我收到了你的問題。 偽代碼

編輯

foreach (var type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
      if (type.Name.Equals("MyClass"))
      {
          MethodInfo mi = type.GetMethod("GetInstance", BindingFlags.Static);
          object o = mi.Invoke(t, null);
          break;
      }
}

應該管用..

雖然其他人給你你所要求的,這可能是你想要的:

IFriut GetFruit(string fruitName)
{
   switch(fruitName)
   {
       case "Apple":
          return Apple.GetInstance();
       case "Banana":
          return Banana.GetInstance();
       default:
          throw new ArgumentOutOfRangeException();
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM