如何在C#中使用泛型动态对象 [英] How to use dynamic object with generics in C#
问题描述
我创建了一个动态对象。我需要将此作为泛型类型传递给方法。我怎么能达到同样的目的?
例如:
说我有动态对象obj,我必须获取此对象的类型并将其传递给期望泛型的方法。
类型type = obj.GetType();
示例 - ClassA< t> class = new ClassA< t>();
我尝试过:
我试图将类型为动态对象obj的类型变量传递给ClassA< t> class = new ClassA< t>();但这不起作用。
任何想法如何处理这种情况?
Hi,
I have a dynamic object created. I need to pass this as a generic type to a method. How would I able to achieve the same ?
Example :
Say I'm having an dynamic object obj, I have to fetch the type of this object and pass it to the method which expects a generic.
Type type = obj.GetType();
example - ClassA<t> class = new ClassA<t>();
What I have tried:
I have tried to pass type variable which has type of dynamic object obj to the ClassA<t> class = new ClassA<t>(); but this doesn't work.
Any idea how to handle this scenario ?
推荐答案
你将无法直接创建一个类的强类型实例,因为编译器没有足够的信息来知道封闭的泛型类型是什么。
您可以创建一个后期绑定的实例使用反射的类型:
You won't be able to directly create a strongly-typed instance of the class, as the compiler doesn't have enough information to know what the closed generic type is.
You can create a late-bound instance of the type using reflection:
Type t = obj.GetType();
Type myType = typeof(ClassA<>).MakeGenericType(t);
object instance = Activator.CreateInstance(myType);
或者您可以使用反射来调用创建和使用实例的通用方法:
Or you can use reflection to call a generic method to create and use the instance:
static class Helper
{
private static readonly MethodInfo DoStuffMethod = typeof(Helper).GetMethod("DoStuffHelper", BindingFlags.NonPublic | BindingFlags.Static);
private static void DoStuffHelper<T>(T value)
{
var instance = new ClassA<T>();
...
}
public static void DoStuff(object value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
Type t = value.GetType();
MethodInfo m = DoStuffMethod.MakeGenericMethod(t);
m.Invoke(null, new[] { value });
}
}
这篇关于如何在C#中使用泛型动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!