我有一个通用类,我希望强制类型参数的实例始终可以从字符串“转换/转化”。是否可以在不使用接口的情况下实现这一点?
可能的实现方式:
public class MyClass<T> where T : IConvertibleFrom<string>, new()
{
public T DoSomethingWith(string s)
{
// ...
}
}
理想的实现方式:
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();
}
// ...
}
}
我更喜欢这种“理想”的实现方式,主要是为了不强制所有的 T 实现 IConvertibleFrom<> 接口。