특정 속성의 PropertyInfo를 얻는 방법은 무엇입니까?
특정 속성에 대한 PropertyInfo를 얻고 싶습니다. 다음을 사용할 수 있습니다.
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
하지만 다음과 비슷한 방법이 있어야합니다.
typeof(MyProperty) as PropertyInfo
거기 있어요? 아니면 유형이 안전하지 않은 문자열 비교를 계속하고 있습니까?
건배.
nameof()
C # 6의 일부이며 Visual Studio 2015에서 사용할 수 있는 new 연산자를 사용할 수 있습니다 . 자세한 내용은 여기 .
예를 들어 다음을 사용합니다.
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
컴파일러는 nameof(MyObject.MyProperty)
"MyProperty"문자열 로 변환 되지만 Visual Studio, ReSharper 등은 nameof()
값 을 리팩터링하는 방법을 알고 있기 때문에 문자열을 변경하지 않고도 속성 이름을 리팩터링 할 수 있다는 이점을 얻을 수 있습니다.
Expression
문자열을 사용하지 않는 lambdas /와 함께 .NET 3.5 방법이 있습니다.
using System;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
static class Program
{
static void Main()
{
PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);
}
}
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
다음과 같이 할 수 있습니다.
typeof(MyObject).GetProperty("MyProperty")
However, since C# doesn't have a "symbol" type, there's nothing that will help you avoid using string. Why do you call this type-unsafe, by the way?
Reflection is used for runtime type evaluation. So your string constants cannot be verified at compile time.
참고URL : https://stackoverflow.com/questions/491429/how-to-get-the-propertyinfo-of-a-specific-property
'Nice programing' 카테고리의 다른 글
https URL에 Net :: HTTP.get 사용 (0) | 2020.10.13 |
---|---|
CS1617 : / langversion에 대한 잘못된 옵션 '6'; (0) | 2020.10.13 |
자체 작업 버튼을 사용하여 스낵바를 닫는 방법은 무엇입니까? (0) | 2020.10.13 |
ASP.NET MVC / WebAPI 응용 프로그램에서 HTTP OPTIONS 동사를 지원하는 방법 (0) | 2020.10.13 |
Dataframe을 csv에 s3 Python에 직접 저장 (0) | 2020.10.13 |