29 Ocak 2009, PERŞEMBE
Nasıl belirli bir özelliği döndürmek için propertyınfo almak için?
Belirli bir özellik için döndürmek için propertyınfo almak istiyorum. İşime yarayabilir:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
Ama benzer bir şey yapmak için bir yolu olmalı
typeof(MyProperty) as PropertyInfo
Orada mı? Ya da tip-güvenli olmayan bir dize karşılaştırması bunları yapmak zorunda mıyım?
Şerefe.
CEVAP
29 Ocak 2009, PERŞEMBE
Bir yoktur .Dizeleri kullanmayanExpression
/Lambda ile NET 3.5 gibi
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;
break;
default:
throw new InvalidOperationException();
}
}
}
Bunu Paylaş:
Nasıl Gıt belirli revizyon tek bir dos...
Nasıl Çekirdek Veri belirli bir Nesne ...
Nasıl belirli bir öznitelik ile özelli...
Nasıl JodaTime ile belirli bir ayın so...
Nasıl LoaderException özelliği almak i...