可能重复:
从字符串名称在程序集中创建类实例
使用类型的字符串表示MyClass
我想MyClass
从它的字符串表示中创建一个实例。
请参阅我的代码中的注释:
interface MyData
{
string Value { get; }
}
class MyClass : MyData
{
public MyClass(string s)
{
Value = s;
}
public string Value { get; private set; }
public static explicit operator MyClass(string strRep)
{
return new MyClass(strRep);
}
public static implicit operator string(MyClass inst)
{
return inst.Value;
}
}
class Program
{
static void Main(string[] args)
{
MyClass inst = new MyClass("Hello World");
string instStr = inst; //string representation of MyClass
string instTypeStr = inst.GetType().FullName;
// I want to be able to do this:
MyData copyInst = (instTypeStr)instStr; // this would throw an error if instTypeStr did not inherit MyData
// Then eventually:
if (instTypeStr.Equals("MyClass"))
{
MyClass = (MyClass)copyInst;
}
}
}