2013-08-14 3 views
2
을 입력하십시오.

이것은 가장 기본적인 것처럼 보이지만 어쨌든 저는 대답을 찾을 수 없습니다.맞춤 클래스 멤버를 입력하고

public class WineCellar 
{ 
    public string year; 
    public string wine; 
    public double nrbottles; 
} 

가 지금은 기능을 원하는 :

WineCellar ex = new WineCellar(); 
ex.members(); 

이 반환해야합니다 : 년, 와인, nrbootles

나는 사용자 정의 클래스를 갖고 있다고 할 수 있습니다.

그리고 :

ex.members().types(); 

가 반환해야합니다 : 문자열, 문자열, 내가 같은 음에 맞춰

을 두 번, 당신은 하나 개의 인스턴스가 있다고 가정 할 수 있습니다 {2010, 오자, 6}. 인덱싱을 통해이를 반환하는 구문이 있습니까? 즉

ex[1] 

또는 2010을 반환

ex.{1} 

?

죄송합니다. 기본 질문입니다.

+0

글쎄, 내가 ex.gettype()을 수행하면 winecellar를 반환하지만 그건 내가 원하는 것이 아니다. 아무 것도 맞지 않는 것 같습니다. – nik

+5

주목할 점은 배열은 인덱스가 제로이므로 ex [1]은'year'가 아닌'wine'의 값을 반환합니다. 실제 질문에 관해서는, 당신이 이것을하기위한 특별한 이유가 있습니까? 더 큰 문제를 해결하기 위해 그것을 사용하려고한다면, 거의 확실하고 쉽고 좋은 방법이 있습니다. – Michelle

+1

@Michelle과 동의합니다. http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem –

답변

3

같은 속성으로 변수를 변경해야합니다,이 더 큰 문제에 대한 잘못된 접근처럼 들린다. 일반적으로 반사가 느리기 때문에 이러한 방법 모두 매우 느린 것을

//returns a list of propertyInfo objects for the class 
// with all kinds of usefull information 
public List<PropertyInfo> GetMemberInfos() 
{ 
    return this.GetType().GetProperties().ToList(); 
} 

//returns a list of property names 
public List<string> GetMemberNames 
{ 
    return this.GetType().GetProperties().Select(pi => pi.Name).ToList(); 
} 

//returns a list of names of the property types 
public List<string> GetMemberTypeNames 
{ 
    return this.GetType().GetProperties().Select(pi => pi.PropertyType.Name).ToList(); 
} 

//indexer that uses the property name to get the value 
//since you are mixing types, you can't get more specific than object 
public object this[string property] 
{ 
    get { return this.GetType().GetProperty(property).GetValue(this); } 
    set { this.GetType().GetProperty(property).SetValue(this, value); } 
} 

//indexer that uses the property index in the properties array to get the value 
public object this[int index] 
{ 
    get { return this.GetType().GetProperties()[index].GetValue(this); } 
    set { this.GetType().GetProperties()[index].SetValue(this, value); } 
} 

참고 : 사물의 종류를 필요로하는 경우에

그러나, 당신은 사용하여 반사를 얻을 수 있습니다. 속도를 높이기 위해 캐시를 시도 할 수 있습니다.

또한 마지막 방법은 완전히 위험합니다입니다. 보장 된 순서가없는 배열을 읽고 쓰려고합니다.사실, documentation 지정 다음 GetProperties를 메소드는 알파벳 또는 선언 순서로서 특정 위해 등록을 반환하지 않는

. 순서가 달라 지므로 코드가 인 경우 속성이 반환되는 순서에 따라 달라지지 않아야합니다.

public class WineCellar 
{ 
    public string year; 
    public string region; 
    public string wine; 
    public double nrbottles; 
} 

하고 대신 wine 재산, 대부분 지금 region 속성을 업데이트합니다 winecellar[1] = "Pinot Noir"를 사용하여 사용되었다 : 당신이 당신의 클래스를 변경하는 경우 예를 들어

.

+0

+1 작은 노트.이 경우 GetProperties 대신'GetFields'가되어야합니다. (비록 이것이 다시 OP의 원하는 접근 방식이 얼마나 깨지기 쉬운 지에 대한 빛을 던지기는하지만). –

+0

@DaxFohl 나는 이것들이 사실 공개 필드 (오, 공포)라고 완전히 놓쳤다. – SWeko

+0

답변 해 주셔서 감사합니다. 이제 이해가된다. 이것은 매우 나쁜 접근입니다. 어쩌면 역 동성을 남기는 것이 낫습니다. 큰 질문은 여기에 게시 : [링크] (http://stackoverflow.com/questions/18235414/dynamically-adjust-create-table-and-insert-into-statement-based-on-custom-class) - 제안이있는 경우 그것은 매우 환영받을 것입니다! – nik

0

당신은 값을 얻기 위해 반사

foreach (var prop in typeof(WineCellar).GetProperties()) 
      { 

       if (prop.PropertyType == typeof(double) || prop.PropertyType == typeof(double?)) 
       { 

       } 
      } 

사용할 수 있습니다, 당신은 할 수 있습니다 :

prop.GetValue(obj); 
1

이 (당신이 문자열로 속성 이름을 원하는 경우 경우) 당신은 회원의 방법을 구현하는 것이 방법이다

public List<string> Members() 
{ 
    List<string> propNames = new List<string>(); 
    foreach (var prop in typeof(WineCellar).GetProperties()) 
    { 
     propNames.Add(prop.Name); 
    } 
    return propNames; 
} 

그리고 이것은 (같은 경우) 당신이 유형을 구현하는 것이 방법이다

이러한 방법이 작동하는
public List<string> Types() 
{ 
    List<string> propTypes = new List<string>(); 
    foreach (var prop in typeof(WineCellar).GetProperties()) 
    { 
     propTypes.Add(prop.PropertyType.ToString()); 
    } 
    return propTypes ; 
} 

그리고이 전 같은 매개 변수의 값을 얻으려면 마지막 일 [N] 당신은이

public string this[int n] 
{ 
    get 
    { 
     int current = 0; 
     foreach (var prop in typeof(WineCellar).GetProperties()) 
     { 
      if (current == n) 
      return prop.GetValue(this, null).ToString(); 
      current++; 
     } 
     return null; 
    } 
} 

처럼 클래스의 간단한 인덱서를 만들 수 있지만, 미셸은 코멘트에 말했듯이

public class WineCellar 
{ 
    public string Year { get; set; } 
    public string Wine { get; set; } 
    public double Nrbottles { get; set; } 
} 
관련 문제