C#
[C#] 클래스의 속성에 변수로 접근하기
Minius
2023. 1. 5. 13:29
반응형
구글에 검색은 아래와 같이 하였다.
c# access class property by name
그 중 첫번째 결과에 들어갔고,
https://stackoverflow.com/questions/10283206/setting-getting-the-class-properties-by-string-name
Setting/getting the class properties by string name
What I'm trying to do is setting the value of the property in a class using a string. For example, my class has the following properties: myClass.Name myClass.Address myClass.PhoneNumber myClass.
stackoverflow.com
아래왜 같은 결과를 얻을 수 있었다.
public class MyClass
{
public object this[string propertyName]
{
get
{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set
{
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
myPropInfo.SetValue(this, value, null);
}
}
}
위와 같이 MyClass 라는 클래스가 있고, 그 안에 위와 같은 코드를 작성하면,
MyClass["변수"] 와 같이 접근할 수 있다.