gpt4 book ai didi

c# - 我如何通过带有反射 C# 的属性获取类信息

转载 作者:太空宇宙 更新时间:2023-11-03 13:32:20 25 4
gpt4 key购买 nike

我有代码:

// entity
public class PermissInfo
{
public int PermissValue { get; set; }
}

// used class
public class MenuPermiss
{
public static readonly PermissInfo PermissView = new PermissInfo { PermissValue = 1 };
public static readonly PermissInfo PermissEdit = new PermissInfo { PermissValue = 2 };
public static readonly PermissInfo PermissDelete = new PermissInfo { PermissValue = 4 };
}

并实现如下代码:

// implement class: check permiss
public static class ImplementClass
{
// used like: return CheckPermiss(MenuPermiss.PermissEdit);
public static bool CheckPermiss(PermissInfo permiss)
{
// How to get "MenuPermiss" class info by "permiss" param

return false;
}
}

如何通过 MenuPermiss.PermissEdit 参数获取 MenuPermiss CLASS?

最佳答案

不可能使用这种语法:

ImplementClass.DoSomething(MyClass.MyProperty);

但这个可能:

ImplementClass.DoSomething(() => MyClass.MyProperty);

解决方法:

using System.Linq.Expressions;

public static class ImplementClass
{
public static bool DoSomething<T>(Expression<Func<T>> propertyExpression)
{
var memberInfo = ((MemberExpression)propertyExpression.Body).Member;
var declaringType = memberInfo.DeclaringType;

Console.WriteLine(declaringType.Name); // outputs "MyClass"

return false;
}
}

关于c# - 我如何通过带有反射 C# 的属性获取类信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062496/

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