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

  • CrazyMan

    CrazyMan

    14 Mayıs 2008
  • HowcastTechGadgets

    HowcastTechG

    22 EYLÜL 2010
  • wowchick16

    wowchick16

    17 Mart 2007