标题有点模糊.我想知道的是,如果可能的话:
string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
Run Code Online (Sandbox Code Playgroud)
显然,MyGenericClass被描述为:
public class MyGenericClass<T>
Run Code Online (Sandbox Code Playgroud)
现在,编译器抱怨'找不到类型或命名空间'myType'."必须有办法做到这一点.
想象一下,您已经获得了两个System.Type,并且您想确定是否存在从一个到另一个的隐式或显式类型转换.
如果没有专门检查静态方法,是否有内置方法来确定该类型是支持这些转换还是这些转换?
我知道这是一个简短的问题,但我认为这个场景相对容易解释,如果不是,请告诉我.
斯蒂芬,提前谢谢.
我有一个泛型类,我想强制类型参数的实例始终从String"cast-able"/ convertible.没有例如使用接口可以做到这一点吗?
可能的实施:
public class MyClass<T> where T : IConvertibleFrom<string>, new()
{
public T DoSomethingWith(string s)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
理想的实施:
public class MyClass<T>
{
public T DoSomethingWith(string s)
{
// CanBeConvertedFrom would return true if explicit or implicit cast exists
if(!typeof(T).CanBeConvertedFrom(typeof(String))
{
throw new Exception();
}
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢这种"理想"实现的原因主要是为了不强迫所有Ts实现IConvertibleFrom <>.