0

我有一个特定类型 ( 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);
}
4

1 回答 1

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
}
于 2012-04-06T11:51:31.143 回答