0
Type hai = Type.GetType("TestStringObject", true);
var obj = (Activator.CreateInstance(hai));
tata = CreateClass<obj>();
我想要做这样的事情,但泛型类不承认obj作为一个对象或类型?我想通过一个对象或类型到一个类,接受一个通用类型
我可以这样做吗?
Type hai = Type.GetType("TestStringObject", true);
var obj = (Activator.CreateInstance(hai));
tata = CreateClass<obj>();
我想要做这样的事情,但泛型类不承认obj作为一个对象或类型?我想通过一个对象或类型到一个类,接受一个通用类型
我可以这样做吗?
在你的例子中,当它是一个对象的实例时,你使用obj
作为一个类型。泛型类型参数必须是类,而不是实例或类型,并且必须在编译时知道。
如果TestStringObject
是在你的项目中的一类,你可以使用它作为泛型类型参数,如下所示:
tata = CreateClass<TestStringObject>();
如果你不知道在编译时的类型,你可以创建一个通用的方法在运行时匹配未知类型(以字符串形式提供),并以这种方式调用泛型方法。在下面的示例中,我将假设有一个名为TestStringObject
的类,该类具有名为CreateClass
的通用方法;您的具体情况可能会有所不同,但这应该完成你所需要的:
TestStringObject:
namespace Test
{
class TestStringObject
{
public void CreateClass<T>()
{
Console.WriteLine("CreateClass Invoked");
}
}
}
别处......
// Get the type of the unknown type, provided here as a string.
Type type = Type.GetType("Test.TestStringObject", true);
// Create an instance of the unknown type.
object obj = Activator.CreateInstance(type);
// Get a reference to the 'CreateClass' generic method info.
MethodInfo method = type.GetMethod("CreateClass");
// Get a reference to a version of the generic method that accepts the unknown type as a generic type argument.
MethodInfo genericMethod = method.MakeGenericMethod(type);
// Invoke the generic method of the unknown type.
genericMethod.Invoke(obj, new object[] { });
请注意命名空间,它必须包含在调用GetType
,因为它需要一个完全合格的名称。
您是否可以提供'CreateClass'的代码并提供您正在接收的错误消息(如果有的话)? – Chase
使用JsonConvert.DeserializeObject替换CreateClass <>接受通用对象的任何类.... –
“TestStringObject”是您项目中的类吗?你是否使用'GetType',因为直到运行时才知道类型? – Chase