获取C#中的属性名称
本文关键字:属性 获取 | 更新日期: 2023-09-27 18:21:20
我有一个对象A,对象A内部是对象B,对象B内部是对象C,对象C有一个名为Text
的属性。
传递"A.B.C.Text"时,如何获取属性Text
的全名?我所说的全名是指A.B.C.Text
,而不是命名空间。
这样定义对象:
class ObjectA
{
public ObjectB ObjB { get; set; }
}
class ObjectB
{
public ObjectC ObjC { get; set; }
}
class ObjectC
{
public string Text { get; set; }
}
然后你可以这样做:
public static void GenericTester()
{
var objA = new ObjectA {ObjB = new ObjectB {ObjC = new ObjectC {Text = "Hello"}}};
Console.WriteLine(objA.ObjB.ObjC.Text);
}
这运行良好(我从http://satalketo.com/2013/10/avoid-magic-strings/):这个类是检索名称的类:
public static class @string
{
private static string GetMemberName(Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.MemberAccess:
var memberExpression = (MemberExpression)expression;
var supername = GetMemberName(memberExpression.Expression);
if (String.IsNullOrEmpty(supername))
return memberExpression.Member.Name;
return String.Concat(supername, '.', memberExpression.Member.Name);
case ExpressionType.Call:
var callExpression = (MethodCallExpression)expression;
return callExpression.Method.Name;
case ExpressionType.Convert:
var unaryExpression = (UnaryExpression)expression;
return GetMemberName(unaryExpression.Operand);
case ExpressionType.Constant:
case ExpressionType.Parameter:
return String.Empty;
default:
throw new ArgumentException("The expression is not a member access or method call expression");
}
}
public static string of<T>(Expression<Func<T>> expression)
{
return GetMemberName(expression.Body);
}
public static string of(Expression<Action> expression)
{
return GetMemberName(expression.Body);
}
public static string of<T>()
{
return typeof(T).Name;
}
}
然后我定义了类:
class A
{
public A()
{
B = new B();
}
public B B { get; set; }
}
class B
{
public B()
{
C = new C();
}
public C C { get; set; }
}
class C
{
public String Text { get; set; }
}
最后,我只调用乞讨中创建的函数
A a = new A();
Console.Write(@string.of(() => a.B.C.Text));
//这将打印a.B.C.文本