2013-09-24 38 views
0

我试着通过相同名称的字符串传递类型和参考的通用用途:转换字符串 - >键入泛型

IE:字符串BUTTONNAME ==“ActionOne” ~~~~~ >>类型== ActionOne,参考== ActionOne

不幸的是,我不知道这是什么正确的语法,我很难通过谷歌找到它,所以如果有人知道如何做到这一点,或者至少它叫什么,这将有助于巨额!

谢谢,这里是我想要做的一些sudo代码!

public class ActionPanelButton : *NotImportant* { 
    private string ButtonName; 
    private Type ButtonType; 

    void ActionPanelButton(){ 
      ButtonName = this.Button.name; // This is return a string set by the user 
      ButtonType = Type.GetType(ButtonName); 
      ActionPanel = this.Button.parent.ActionPanel; // This will return the containing panel object 
    } 

    public void LeftClick(){ //This responds like any-ol OnClick 

     ActionPanel.ChangeSelectedActionBundle<(ButtonType)>(ActionPanel.DisplayedActionPanel.(ButtonType)); 
    } 
} 

公共类ActionPanel ....

public void ChangeSelectedActionBundle <T> (T action){ 

     Type typeOfObject = typeof(ActionBundle); 
     Type typeOfAction = typeof(T); 

     FieldInfo field = typeOfObject.GetField(typeOfAction.Name); 
     field.SetValue(SelectionManager.SelectedActionBundle, action); 
    } 
+0

由于泛型通过编译器工作,所以需要在编译时知道类型。没有真正简单的方法去做你正在做的事情,而不是使用反思。 –

+0

我很难理解你在做什么。你能否改变这个例子?它确实出现,虽然反射更多的是你以后..不是泛型。 –

+0

只要我回家,我会扩大我的背景!感谢您的帮助! – Burdock

回答

1

泛型函数实际上不止一个运行特征的编译器功能。当编译器运行到这样的代码:

myObj.Foo<Int32>(123); 

它将使用的Int32代替T创建Foo的实现。出于这个原因,你不能使用只被称为运行时的类型来调用泛型函数。

但是,我质疑你为什么需要这样做。你的已经在你的ChangeSelectedActionBundle方法中使用反射。它不需要是通用的。你可以这样做:

public void ChangeSelectedActionBundle(object action) 
{ 
    Type typeOfObject = typeof(ActionBundle); 
    Type typeOfAction = action.GetType(); 

    FieldInfo field = typeOfObject.GetField(typeOfAction.Name); 
    field.SetValue(SelectionManager.SelectedActionBundle, action); 
} 

也许不是使用object,你可以使用常见的基类,以你的所有行动,或使用一个接口。

相关问题