SORU
9 EYLÜL 2009, ÇARŞAMBA


'' yansıması ile döküm

Düşünün aşağıdaki örnek kod:

class SampleClass
{
    public long SomeProperty { get; set; }
}

public void SetValue(SampleClass instance, decimal value)
{
    // value is of type decimal, but is in reality a natural number => cast
    instance.SomeProperty = (long)value;
}

Şimdi bir şey yansıması ile benzer yapmak istiyorum:

void SetValue(PropertyInfo info, object instance, object value)
{
    // throws System.ArgumentException: Decimal can not be converted to Int64
    info.SetValue(instance, value)  
}

Bu döndürmek için propertyınfo her zaman uzun, ne de o değeri her zaman bir ondalık temsil ettiğini kabul edemem unutmayın. Ancak, bu değeri bu özellik için doğru türü için döküm olabilir biliyorum.

Nasıl "değer", türü yansıma yoluyla döndürmek için propertyınfo örneği tarafından temsil edilen parametre ? dönüştürebilir miyim

CEVAP
9 EYLÜL 2009, ÇARŞAMBA


void SetValue(PropertyInfo info, object instance, object value)
{
    info.SetValue(instance, Convert.ChangeType(value, info.PropertyType));
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • cekehechu

    cekehechu

    20 HAZİRAN 2006
  • Kap Slap

    Kap Slap

    8 Mart 2010
  • Wii Minute Radio

    Wii Minute R

    31 Mayıs 2008