给定类型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) 我正在尝试编写将从参数列表中推断出类型的代码,然后调用与这些参数匹配的方法.这非常有效,除非参数列表中包含null
值.
我想知道如何使Type.GetMethod
调用匹配函数/重载,即使null
参数列表中的参数.
object CallMethodReflection(object o, string nameMethod, params object[] args)
{
try
{
var types = TypesFromObjects(args);
var theMethod = o.GetType().GetMethod(nameMethod, types);
return (theMethod == null) ? null : theMethod.Invoke(o, args);
}
catch (Exception ex)
{
return null;
}
}
Type[] TypesFromObjects(params object[] pParams)
{
var types = new List<Type>();
foreach (var param in pParams)
{
types.Add((param == null) ? null : param.GetType());
}
return types.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
主要问题是types.Add((param == null) ? null : …