2012-11-07 13 views
16

long? türünde bir int ile doldurulmuş bir özelliğimiz var.Yansıma özelliğini belirlerken türü dönüştürme sorunu

ben sadece doğrudan obj.Value = v; özelliğini ayarlayın ama denemek ve yansıma info.SetValue(obj, v, null); yoluyla özelliğini ayarlayın zaman bana şu istisna verdiğinde Bu çalışıyor: Çeşidi

Object 'System.ınt32' olamaz 'System.Nullable`1 [System.Int64]' türüne dönüştürülür.

Bu basitleştirilmiş senaryo: doğrudan özelliği ayarlanırken çalıştığını ederken reflection yoluyla mülk ayarlarken

class TestClass 
    { 
     public long? Value { get; set; } 
    } 

    [TestMethod] 
    public void TestMethod2() 
    { 
     TestClass obj = new TestClass(); 
     Type t = obj.GetType(); 

     PropertyInfo info = t.GetProperty("Value"); 
     int v = 1; 

     // This works 
     obj.Value = v; 

     // This does not work 
     info.SetValue(obj, v, null); 
    } 

Neden çalışmıyor?

cevap

48

Kontrol Tam makale: How to set value of a property using Reflection?

tam kodu size özellik türü için değer dönüştürmek gerekiyor bu ie gibi değer dönüştürmek gerekiyor

public static void SetValue(object inputObject, string propertyName, object propertyVal) 
{ 
    //find out the type 
    Type type = inputObject.GetType(); 

    //get the property information based on the type 
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); 

    //find the property type 
    Type propertyType = propertyInfo.PropertyType; 

    //Convert.ChangeType does not handle conversion to nullable types 
    //if the property type is nullable, we need to get the underlying type of the property 
    var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType; 

    //Returns an System.Object with the specified System.Type and whose value is 
    //equivalent to the specified object. 
    propertyVal = Convert.ChangeType(propertyVal, targetType); 

    //Set the value of the property 
    propertyInfo.SetValue(inputObject, propertyVal, null); 

} 
private static bool IsNullableType(Type type) 
{ 
    return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)); 
} 

null türü değeri ayarı eğer

gibi aşağıdakileri yapmanız gerekir, çünkü Eğer yazarken verilen türe herhangi arbirtary değeri dönüştürmek olamaz ... bu yüzden bu

+0

Mükemmel cevap! – series0ne

+0

Gecikme için özür dilerim, kod örnekleri ile uğraşmaktaydı. Bu hile yaptı, teşekkürler! – Shikyo

+0

'Boş' ayarlandığında çalışmaz. Düzeltmek kolaydır, postanızı düzenlemeyi denedi ancak reddedildi. – Shikyo

2

gibi dönüştürmek gerekir:

obj.Value = v; 

derleyici sizin için uygun döküm yapmak bilen ve aslında

derler
obj.Value = new long?((long) v); 

Kullanım yansımanız olduğunda, size yardımcı olacak bir derleyici yoktur.

2

long türünde dolaylı bir dönüştürme yöntemi vardır.

6.1.2 Implicit numeric conversions

Sen = sembolün arkasında mevcut gizli yöntemi olarak örtük dönüştürme yöntemini görebilirsiniz.

Ayrıca null türü ile çalışır:

int i = 0; 
int? j = i; // Implicit conversion 
long k = i; // Implicit conversion 
long? l = i; // Implicit conversion 

Ancak hiçbir örtük dönüştürme olmayan boş bir null geçmek mevcut olduğundan tersi, çalışmıyor gidiyor:

int? i = 0; 
int j = i; // Compile assert. An explicit conversion exit... 
int k = (int)i; // Compile, but if i is null, you will assert at runtime. 

int ürününü int? veya long? ürününe açıkça dönüştürmek zorunda değilsiniz. Ancak, yansıma kullandığınızda, örtük dönüştürmeyi atlarsınız ve doğrudan değere mülk atamanız gerekir. Bu şekilde, onu açıkça dönüştürmelisiniz.

info.SetValue(obj, (long?)v, null); 

Yansıma = arkasına gizlenmiş tüm tatlı şeyler atlayın.

+0

Böyle bir şeye şüphesi var, açık bir açıklama için teşekkürler. – Shikyo