我有一个泛型类,我想强制类型参数的实例始终从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 <>.