如何检查隐式或显式转换是否存在?

我有一个generics类,我想强制类型参数的实例始终从String“cast-able”/ convertible。 没有例如使用接口可以做到这一点吗?

可能的实施:

public class MyClass where T : IConvertibleFrom, new() { public T DoSomethingWith(string s) { // ... } } 

理想的实施:

 public class MyClass { public T DoSomethingWith(string s) { // CanBeConvertedFrom would return true if explicit or implicit cast exists if(!typeof(T).CanBeConvertedFrom(typeof(String)) { throw new Exception(); } // ... } } 

我更喜欢这种“理想”实现的原因主要是为了不强迫所有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 }); } 

注意反思的成本。

为什么你不能做这样的事情?

 public class MyClass where T : string { public T DoSomethingWith(string s) { // ... } } 

通过这种方式,您可以在DoSomethingWith代码中检查s是否可以转换为T 如果不能,那么你可以抛出exception,或者如果可以的话,你可以抛出exception

 if(!typeof(T).IsAssignableFrom(typeof(String))) { throw new Exception(); }