相关疑难解决方法(0)

如何使用反射来调用泛型方法?

当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?

考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

1002
推荐指数
6
解决办法
24万
查看次数

动态创建模板的泛型类型

我正在使用ChannelFactory编写WCF,它需要一个类型来调用CreateChannel方法.例如:

IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...);
Run Code Online (Sandbox Code Playgroud)

在我的情况下,我正在做路由,所以我不知道我的渠道工厂将使用什么类型.我可以解析一个消息头来确定类型,但我在那里碰到了一堵砖墙,因为即使我有一个Type I实例也无法传递ChannelFactory期望泛型类型的实例.

用非常简单的术语重述这个问题的另一种方法是我试图做这样的事情:

string listtype = Console.ReadLine(); // say "System.Int32"
Type t = Type.GetType( listtype);
List<t> myIntegers = new List<>(); // does not compile, expects a "type"
List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time?
Run Code Online (Sandbox Code Playgroud)

我可以在C#中使用这种方法吗?

c# generics

14
推荐指数
2
解决办法
2万
查看次数

确定运行时的类型并将其应用于泛型类型 - 我该怎么做?

我想创建一个强类型列表并在运行时决定类型.这是我的代码.我认为它应该工作,但它没有:)

        Type elementType = Type.GetType(parts[0].Trim(),false,true);
        var elementsBeingSet = new List<elementType>();
Run Code Online (Sandbox Code Playgroud)

你有什么想法如何创建一个强类型列表,其类型我将在运行时决定?

重复:这是其他版本:

c# types

7
推荐指数
1
解决办法
7049
查看次数

MethodInfo、CreateDelegate 和通用方法

感谢 Jon Skeet 在这个问题中的回答,我进行了以下工作:

public delegate BaseItem GetItemDelegate(Guid itemID);

public static class Lists
{
  public static GetItemDelegate GetItemDelegateForType(Type derivedType)
  {
    MethodInfo method = typeof(Lists).GetMethod("GetItem");
    method = method.MakeGenericMethod(new Type[] { derivedType });
    return (GetItemDelegate)Delegate.CreateDelegate(typeof(GetItemDelegate), method);
  }

  public static T GetItem<T>(Guid itemID) where T : class { // returns an item of type T ... }
}

public class DerivedItem : BaseItem { }

// I can call it like so:
GetItemDelegate getItem = Lists.GetItemDelegateForType(typeof(DerivedItem));
DerivedItem myItem = getItem(someID); // …
Run Code Online (Sandbox Code Playgroud)

c# generics delegates methodinfo

5
推荐指数
1
解决办法
6520
查看次数

C#:枚举值的通用列表

有没有办法创建一个获取枚举类型作为参数的方法,并从它的值返回枚举基础类型的泛型列表,无论底层类型是否为int\short byte等'...
我看到了这个 Jon Skeet的回答,但看起来太复杂了.

c# generics enums

2
推荐指数
1
解决办法
6482
查看次数

标签 统计

c# ×5

generics ×4

delegates ×1

enums ×1

methodinfo ×1

reflection ×1

types ×1