【发布时间】:2013-09-30 08:14:51
【问题描述】:
我试图通过同名字符串传递类型和对泛型的引用:
IE: string ButtonName == "ActionOne" ~~~~~>> Type == ActionOne, reference == 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);
}
【问题讨论】:
-
由于泛型通过编译器工作,因此需要在编译时知道类型。除了使用反射之外,没有一种简单的方法可以做你正在做的事情。
-
我很难理解你在追求什么。你能不能换个例子?尽管反射似乎更像是您所追求的……而不是泛型。
-
一回到家,我就展开我的语境!!感谢您的帮助!
-
@Burdock - 他们想调用一个基于仅在运行时才知道的类型的泛型方法。
-
@MikeChristensen 说得对~让我检查一下我的代码,我会更新帖子...
标签: c# string generics syntax types