(参见下面我使用我接受的答案创建的解决方案)
我正在尝试提高一些涉及反射的代码的可维护性.该应用程序有一个.NET Remoting接口,公开(除此之外)一个名为Execute的方法,用于访问未包含在其已发布的远程接口中的应用程序部分.
以下是应用程序如何指定可通过Execute访问的属性(本例中为静态属性):
RemoteMgr.ExposeProperty("SomeSecret", typeof(SomeClass), "SomeProperty");
Run Code Online (Sandbox Code Playgroud)
所以远程用户可以调用:
string response = remoteObject.Execute("SomeSecret");
Run Code Online (Sandbox Code Playgroud)
并且应用程序将使用反射来查找SomeClass.SomeProperty并将其值作为字符串返回.
不幸的是,如果有人重命名SomeProperty并忘记更改ExposeProperty()的第3个parm,它会破坏这种机制.
我需要相当于:
SomeClass.SomeProperty.GetTheNameOfThisPropertyAsAString()
Run Code Online (Sandbox Code Playgroud)
在ExposeProperty中用作第三个parm,因此重构工具将负责重命名.
有没有办法做到这一点?提前致谢.
好的,这是我最终创建的内容(根据我选择的答案和他引用的问题):
// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
var me = propertyLambda.Body as MemberExpression;
if (me == null)
{ …Run Code Online (Sandbox Code Playgroud) 我有一个表达式指向我的类型的属性.但它并不适用于每种房产类型."不代表"意味着它会导致不同的表达类型.我认为它会导致a
MemberExpression但事实并非如此.
对于int和Guid它导致一个UnaryExpression和string
在MemberExpression.
我有点困惑 ;)
我的课
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
测试代码
Person p = new Person { Age = 16, Name = "John" };
Expression<Func<Person, object>> expression1 = x => x.Age;
// expression1.Body = UnaryExpression;
Expression<Func<Person, object>> expression2 = x => x.Name;
// expression2.Body = MemberExpression;
Run Code Online (Sandbox Code Playgroud)
我如何比较两个表达式并检查它们是否意味着相同的类型和相同的属性?
感谢用户dasblinkenlight带我走上正轨. …
我正在构建一个类型的属性列表,以包含在该类型集合的导出中.我想这样做而不使用字符串作为属性名称.只有该类型的某些属性才会包含在列表中.我想做点什么:
exportPropertyList<JobCard>.Add(jc => jc.CompletionDate, "Date of Completion");
Run Code Online (Sandbox Code Playgroud)
我该如何实现这种通用的Add方法?顺便说一句,字符串是属性的描述.