2014-06-19 4 views
0

무엇일부 코드에 대한 설명이 필요합니다.

public object this[string name] 

가 할

class ObjectWithProperties 
{ 
    Dictionary<string, object> properties = new Dictionary<string, object>(); 

    public object this[string name] 
    { 
     get 
     { 
      if (properties.ContainsKey(name)) 
      { 
       return properties[name]; 
      } 
      return null; 
     } 
     set 
     { 
      properties[name] = value; 
     } 
    } 
} 
+0

당신이 여기에있는 것은 인덱싱 된 속성에, 당신 여기에서 더 많은 abou를 읽을 수 있습니다. http://msdn.microsoft.com/en-gb/library/aa288464(v=vs.71).aspx –

답변

6

당신은 귀하의 경우 (즉, 프로퍼티 이름)

를 인덱스를 사용하지 않는 개체에서 직접 사전에서 값을 참조 할 수있을 것이다 그것은

var foo = new ObjectWithProperties(); 
foo["bar"] = 1; 
foo["kwyjibo"] = "Hello world!" 

// And you can retrieve them in the same manner... 

var x = foo["bar"]; // returns 1 

MSDN 가이드 : http://msdn.microsoft.com/en-gb/library/2549tw02.aspx

기본 튜토리얼 : http://www.tutorialspoint.com/csharp/csharp_indexers.htm

편집 주석의 질문에 대답 :

이것은 다음과 같은 일을하는 것과 같습니다

class ObjectWithProperties 
{ 
    public Dictionary<string, object> Properties { get; set; } 

    public ObjectWithProperties() 
    { 
     Properties = new Dictionary<string, object>(); 
    } 
} 

// instantiate in your other class/app/whatever 
var objWithProperties = new ObjectWithProperties(); 
// set 
objWithProperties.Properties["foo"] = "bar"; 
// get 
var myFooObj = objWithProperties.Properties["foo"]; // myFooObj = "bar" 
+0

이 [string name]의 공용 객체에서 이것의 중요한 의미는 무엇입니까? –

+0

MSDN 문서에 설명 된대로 간단히 "구문상의 편의" – Rich

+0

위의 코드에서 공용 객체 대신 [string name]이 (가) 더 이상 다른 방법이 있습니까 :) –

관련 문제