简体   繁体   中英

How can I get class information by property w/ reflection C#

I have code:

// 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 };
}

And implement code like:

// 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;
    }
}

How can i get MenuPermiss CLASS by MenuPermiss.PermissEdit param?

It is not possible using this syntax:

ImplementClass.DoSomething(MyClass.MyProperty);

but possible with this one:

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

Solution:

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;
    }
}

Link reference here :

It work good with syntax:

PermissHelper.CheckPermiss(()=>MenuPermiss.PermissDelete) 

I try implement with this code, and it's return "<>c__DisplayClass0" value. How to fix it?

PermissHelper.CheckPermiss(MenuPermiss.PermissDelete) 

and

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 : "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM