相关疑难解决方法(0)

如何判断A类是否可以隐式转换为B类

给定类型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)

.net reflection type-conversion implicit-conversion

22
推荐指数
3
解决办法
6609
查看次数

使用Reflection调用方法时处理null参数

我正在尝试编写将从参数列表中推断出类型的代码,然后调用与这些参数匹配的方法.这非常有效,除非参数列表中包含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 : …

c# reflection null

8
推荐指数
2
解决办法
3837
查看次数