【问题标题】:Converting String -> Type for uses with generics转换字符串 -> 类型以用于泛型
【发布时间】: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


【解决方案1】:

泛型函数实际上更多是编译器功能而不是运行时功能。当编译器遇到如下代码时:

myObj.Foo<Int32>(123);

它将创建使用Int32 而不是TFoo 实现。因此,您不能使用仅称为运行时的类型调用泛型函数。

但是,我质疑您为什么需要这样做。您已经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

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 2013-05-15
    • 1970-01-01
    • 2011-06-29
    • 2021-10-25
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    相关资源
    最近更新 更多