2010-08-09 5 views
5

구문 분석하는 파일의 일부 데이터를 저장하는 간단한 도우미 클래스를 설정하고 있습니다. 등록 정보의 이름은 파일에서 찾을 것으로 예상되는 값의 이름과 일치합니다. 명시 적으로 이름을 지정하지 않고 속성에 값을 할당 할 수 있도록 AddPropertyValue이라는 메서드를 클래스에 추가하고 싶습니다.속성 이름을 문자열로 전달하고 값을 할당 할 수 있습니까?

방법은 다음과 같을 것이다 :

//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 

을 구현은 다음과 같습니다

의 C#/VB.NET

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

각 테스트하지 않고이 가능 개별 속성 이름은 제공된 propertyName에 대한 값입니까?

+0

이 이전 게시물 매우 유사 : http://stackoverflow.com/questions/110562/how-to-pass-a-generic-property-as-a- 매개 변수 대 함수 – David

답변

7

Type.GetProperty을 호출하고 PropertyInfo.SetValue을 호출하여이를 반영 할 수 있습니다. 실제로 존재하지 않는 속성을 확인하려면 적절한 오류 처리를 수행해야합니다.

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); 
    } 
} 

이 많은 작업을 수행해야하는 경우

, 그것은 성능면에서 꽤 고통이 될 수 있습니다

다음은 샘플입니다. 델리게이트 주위에는 속임수를 사용하는 것이 훨씬 빠르지 만 먼저 작업을 수행하는 것이 좋습니다.

4

당신이 이름을 사용하여 속성을 얻고 값을 설정 반사를 사용하여 ... 뭔가 같은 : 코드를 조직의 관점에서

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

, 당신은 mixin-like 방법으로 그것을 할 수있는 (떨어져 오류 처리) :

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); 
    } 
} 

이 방법, 당신은 그것으로 당신의 소중한 하나의 기본 클래스를 희생하지 않고, 많은 다른 클래스에서 그 논리를 다시 사용할 수 있습니다.

VB.NET에서

:

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

및 get : public static string GetValue (이 IPropertySettable 자체, 문자열 이름) { return self.GetType(). GetProperty (name) .GetValue (self, null) .ToString() ; } –

관련 문제