我有一个泛型类,我想强制类型参数的实例始终从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 <>.
鉴于您想要从密封 String 类型进行转换,您可以忽略可能的可为空、装箱、引用和显式转换。才有op_Implicit()资格。System.Linq.Expressions.Expression 类提供了一种更通用的方法:
using System.Linq.Expressions;
...
public static T DoSomethingWith(string s)
{
var expr = Expression.Constant(s);
var convert = Expression.Convert(expr, typeof(T));
return (T)convert.Method.Invoke(null, new object[] { s });
}
Run Code Online (Sandbox Code Playgroud)
当心反射的成本。
| 归档时间: |
|
| 查看次数: |
2767 次 |
| 最近记录: |