我有两个成员类型作为字符串 - 而不是类型实例.如何检查这两种类型是否可浇铸?假设字符串1是"System.Windows.Forms.Label",另一个是"System.Windows.Forms.Control".如何检查第一个是否是第二个的子类(或隐式可转换)?这是否可以通过使用反射?
感谢你的支持!
我有一个泛型类,我想强制类型参数的实例始终从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 <>.