给定类型a和类型b,我如何在运行时确定是否存在从a到b的隐式转换?
如果这没有意义,请考虑以下方法:
public PropertyInfo GetCompatibleProperty<T>(object instance, string propertyName)
{
var property = instance.GetType().GetProperty(propertyName);
bool isCompatibleProperty = !property.PropertyType.IsAssignableFrom(typeof(T));
if (!isCompatibleProperty) throw new Exception("OH NOES!!!");
return property;
}
Run Code Online (Sandbox Code Playgroud)
这是我想要工作的调用代码:
// Since string.Length is an int property, and ints are convertible
// to double, this should work, but it doesn't. :-(
var property = GetCompatibleProperty<double>("someStringHere", "Length");
Run Code Online (Sandbox Code Playgroud)