我有代码:
// 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 param获取MenuPermiss CLASS?
答案 0 :(得分:1)
使用这种语法是不可能的:
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;
}
}
答案 1 :(得分:0)
链接参考here:
它的语法很好用:
PermissHelper.CheckPermiss(()=>MenuPermiss.PermissDelete)
我尝试使用此代码实现,并返回“&lt;&gt; c__DisplayClass0”值。如何解决?
PermissHelper.CheckPermiss(MenuPermiss.PermissDelete)
和
public static string CheckPermiss(PermissInfo permissInfo)
{
Expression<Func<PermissInfo>> x = () => permissInfo;
var memberInfo = ((MemberExpression)x.Body).Member;
var declaringType = memberInfo.DeclaringType;
return declaringType != null ? declaringType.Name : "";
}