2010-04-15 95 views
5
sTypeName = ... //do some string stuff here to get the name of the type 

/* 
The Assembly.CreateInstance function returns a type 
of System.object. I want to type cast it to 
the type whose name is sTypeName. 

assembly.CreateInstance(sTypeName) 

So, in effect I want to do something like: 

*/ 

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName); 

我該怎麼做?而且,假設這是C#2.0,我該如何在賦值表達式的左側進行操作。我沒有var關鍵字。從類型名稱的字符串表示類型轉換爲類型

回答

2

通常你讓所有的類,你想實例化這個動態的,實現一個通用接口,可以說IMyInterface。您可以從類名字符串像這樣創建一個實例:

Assembly asm = Assembly.GetExecutingAssembly(); 
string classname = "MyNamespace.MyClass"; 
Type classtype = asm.GetType(classname); 

// Constructor without parameters 
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype); 

// With parameters (eg. first: string, second: int): 
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype, 
         new object[]{ 
          (object)"param1", 
          (object)5 
         }); 

即使你沒有一個通用的接口,但知道方法的名稱(如字符串),你可以調用你這樣的方法(很相似屬性,事件等):

object instance = Activator.CreateInstance(classtype); 

int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance, 
         new object[] { 15 }); 
// result = 30 

的示例類:

namespace MyNamespace 
{ 
    public class MyClass 
    { 
     public MyClass(string s, int i) { } 

     public int TwoTimes(int i) 
     { 
      return i * 2; 
     } 
    } 
} 
2

不幸的是,.NET沒有辦法做你想做的事情。

可能的部分解決方案是:

  1. 如果你知道在編譯時的類型(不太可能,因爲你是在從一個字符串運行時創建它),然後簡單地映射到該類型:

    YourType t = (YourType)Activator.CreateInstance(sTypeName); 
    
  2. 如果你知道所有可能的類型將實現一個特定的,通用的接口,那麼你可以到該接口來代替:

    IYourInterface i = (IYourInterface)Activator.CreateInstance(sTypeName); 
    

如果你不能做上述任何一個,那麼不幸的是,你被困在object和反思。

+0

謝謝,我已經完成(2)並正在尋找選項。 – 2010-04-15 09:30:58

2

在類中定義一個通用的方法,然後你可以施放這樣的:

public T Cast<T>(object obj) 
{ 
     return (T) obj; 
} 

string sTypename = "SomeClassName"; 
MethodInfo cast = this.GetType().GetMethod("Cast"); 
MethodInfo genericCast = cast.MakeGenericMethod(new Type[] { Type.GetType(sTypename) }); 
Object castedValue = genericCast.Invoke(this, new object[] { instanceToBeCasted }); 

但後來我想,是什麼就是這樣鑄造的點,如果你不能鑄造值存儲在一個變量實際的類型,正是因爲您在編寫代碼時不知道實際類型?