gpt4 book ai didi

c# - 访问 C# 属性名称或特性

转载 作者:可可西里 更新时间:2023-11-01 07:49:15 24 4
gpt4 key购买 nike

我想从类实例自动生成 SQL 语句。该方法应该类似于 Update(object[] Properties, object PrimaryKeyProperty)。该方法是实例的一部分(类、基方法——对任何 child 都是通用的)。属性数组是类属性的数组,将在更新 语句中使用。属性名称等于表字段名称。

问题是我无法获取属性名称。

是否有任何选项可以在类实例中获取属性名称?示例:

public class MyClass {
public int iMyProperty { get; set; }
public string cMyProperty2 { get; set; }
{

main() {
MyClass _main = new MyClass();

_main.iMyProperty.*PropertyName* // should return string "iMyProperty"

{

我知道 PropertyInfo,但我不知道如何从 GetProperties() 数组中获取属性的 ID。

有什么建议吗?

最佳答案

Just wrote an implementation of this上周二为我们的用户组介绍了 lambda。

  • 你可以做到

    MembersOf .GetName(x => x.Status)

  • 或者

    var a = new Animal() a.MemberName(x => x.Status)

代码:

public static class MembersOf<T> {
public static string GetName<R>(Expression<Func<T,R>> expr) {
var node = expr.Body as MemberExpression;
if (object.ReferenceEquals(null, node))
throw new InvalidOperationException("Expression must be of member access");
return node.Member.Name;
}
}

关于c# - 访问 C# 属性名称或特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1407576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com