2010-08-09 22 views
5

Ayrıştığım bir dosyadan bazı verileri saklamak için basit bir yardımcı sınıf kuruyorum. Özelliklerin adları, dosyada bulmayı beklediğim değerlerin adlarıyla eşleşir. Sınıfıma AddPropertyValue adlı bir yöntem eklemek istiyorum, böylece bir ada sahip olduğu isimle açıkça aramadan bir değer atayabilirim.Bir özellik adının bir dize olarak iletilmesi ve buna değer atanması mümkün mü?

yöntem şu şekilde görünecektir:

//C# 
public void AddPropertyValue(string propertyName, string propertyValue) { 
    //code to assign the property value based on propertyName 
} 

--- 

'VB.NET' 
Public Sub AddPropertyValue(ByVal propertyName As String, _ 
          ByVal propertyValue As String) 
    'code to assign the property value based on propertyName ' 
End Sub 

uygulama aşağıdaki gibi görünebilir:

C#/VB.NET

MyHelperClass.AddPropertyValue("LocationID","5") 

her test etmeden bu mümkün mü ürünle verilen propertyName numaralı ürüne karşı bireysel mülkiyet adı?

+0

bu önceki yazı çok benzer: http://stackoverflow.com/questions/110562/how-to-pass-a-generic-property-as-a- parametre-bir-işlev – David

cevap

7

Bunu Type.GetProperty numaralı telefonu ve ardından PropertyInfo.SetValue numaralı telefonu arayarak yapabilirsiniz. Gerçekte olmamakla birlikte özelliği kontrol etmek için uygun hata işlemlerini yapmanız gerekir.

using System; 
using System.Reflection; 

public class Test 
{ 
    public string Foo { get; set; } 
    public string Bar { get; set; } 

    public void AddPropertyValue(string name, string value) 
    { 
     PropertyInfo property = typeof(Test).GetProperty(name); 
     if (property == null) 
     { 
      throw new ArgumentException("No such property!"); 
     } 
     // More error checking here, around indexer parameters, property type, 
     // whether it's read-only etc 
     property.SetValue(this, value, null); 
    } 

    static void Main() 
    { 
     Test t = new Test(); 
     t.AddPropertyValue("Foo", "hello"); 
     t.AddPropertyValue("Bar", "world"); 

     Console.WriteLine("{0} {1}", t.Foo, t.Bar); 
    } 
} 

Bunu çok şey gerekiyorsa

, bu performans açısından oldukça acı olabilir:

İşte bir örnek verilmektedir. Delegelerin etrafında, daha hızlı bir hale getirebilecek hileler var, ama önce işe yaramaya değer.

4

ismini kullanarak tesisle almak ve değerini ayarlamak yansıma kullanarak ... gibi bir şey: kod düzenleme açısından

Type t = this.GetType(); 
var prop = t.GetProperty(propName); 
prop.SetValue(this, value, null); 
2

, bir mixin-like şekilde yapabileceğini (ayrı taşıma hatası) :

public interface MPropertySettable { } 
public static class PropertySettable { 
    public static void SetValue<T>(this MPropertySettable self, string name, T value) { 
    self.GetType().GetProperty(name).SetValue(self, value, null); 
    } 
} 
public class Foo : MPropertySettable { 
    public string Bar { get; set; } 
    public int Baz { get; set; } 
} 

class Program { 
    static void Main() { 
    var foo = new Foo(); 
    foo.SetValue("Bar", "And the answer is"); 
    foo.SetValue("Baz", 42); 
    Console.WriteLine("{0} {1}", foo.Bar, foo.Baz); 
    } 
} 

Bu şekilde, onunla değerli tek temel sınıfa ödün vermeden, birçok farklı sınıflarda bu mantığı yeniden kullanabilirsiniz.

VB.NET içinde

:

Public Interface MPropertySettable 
End Interface 
Public Module PropertySettable 
    <Extension()> _ 
    Public Sub SetValue(Of T)(ByVal self As MPropertySettable, ByVal name As String, ByVal value As T) 
    self.GetType().GetProperty(name).SetValue(self, value, Nothing) 
    End Sub 
End Module 
+1

Ve get için: genel statik dize GetValue (bu IPropertySettable öz, dize adı) { return self.GetType(). GetProperty (name) .GetValue (self, null) .ToString() ; } –

İlgili konular