【问题标题】:Possible to test a cast to PropertyInfo.PropertyType when object implements implicit operator?当对象实现隐式运算符时,可以测试对 PropertyInfo.PropertyType 的强制转换吗?
【发布时间】:2012-04-06 11:18:36
【问题描述】:

我有一个特定类型的对象 (SpecialImage),它将 隐式运算符 实现为另一种类型 (Image)。

SpecialImage不是派生自Image。但是可以通过操作符进行以下操作:

var someImage = new Image();
(SpecialImage)someImage;

我有一个带有属性的对象,我通过反射和Image 对象循环遍历:

是否可以在尝试设置值之前检查对象是否可转换为 info.PropertyType

var someImage = new Image();

foreach(PropertyInfo info in someOjbect.GetType().GetProperties()) {
    //info.PropertyType == typeof(SomeImage);

    //Is it possible to check if the object is castable to 
    //info.PropertyType before trying to set the value?
    info.SetValue(someObject, someImage, null);
}

【问题讨论】:

    标签: c# reflection casting operator-keyword propertyinfo


    【解决方案1】:

    你可以试试这样的

    如果我们有这些类

    class T1
    {
    }
    
    class T2
    {
        public static implicit operator T1(T2 item) { return new T1(); }
    }
    

    我们可以使用的

    if(typeof(T2).GetMethods().Where (
        t => t.IsStatic && t.IsSpecialName && 
             t.ReturnType == typeof(T1) && t.Name=="op_Implicit").Any())
    {
        // do stuff
    }
    

    【讨论】:

    猜你喜欢
    • 2014-05-21
    • 1970-01-01
    • 2012-01-04
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多