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

  • andyabc45

    andyabc45

    1 Mayıs 2011
  • GUN-TIME with Brandon

    GUN-TIME wit

    3 ŞUBAT 2009
  • TechSmartt

    TechSmartt

    29 Aralık 2010