在C#中,我有一个方法
public string GetString<T>() where T : class
在调用函数中,我只有要传递给GetString()<T>
的类的名称。例如"MyClass"。如何将"MyClass"转换为class
?我尝试使用Type
s,但找不到转换。
编辑:真正的例子来自一个数据库访问类。客户端要求提供特定硬件组件的信息。此组件由字符串指定。基于这个字符串,我想访问一个具有已知名称模式的表。非硬编码表名允许我们在不需要更改C#代码的情况下从数据库中添加/删除表。
返回所需信息的函数已经存在,并且需要class
作为泛型类型。
例如
string tblName = "HW_" + hwComponentFromClient;
string retValue = GetString<GetClassByString(tblName)>();
我需要一种方法:
class GetClassByString(string);
您可以获取类名,但您需要从正确的程序集获取它,并传递类的全名(程序集名+类名,在我的情况下是"TestAlexander.Test"
)。
class Program
{
static void Main(string[] args)
{
Type classType = Assembly.GetExecutingAssembly().GetType("TestAlexander.Test");
Test test = new Test();
typeof(Test).GetMethod("TestMethod").MakeGenericMethod(classType).Invoke(test, null);
Console.Read();
}
}
public class Test
{
public void TestMethod<T>() where T: class
{
Console.WriteLine("Great success!");
}
}