简体   繁体   中英

Associate “Code/Properties/Stuff” with Fields in C# without reflection. I am too indoctrinated by Javascript

I am building a library to automatically create forms for Objects in the project that I am working on.

The codebase is in C#, and essentially we have a HUGE number of different objects to store information about different things. If I send these objects to the client side as JSON, it is easy enough to programatically inspect them to generate a form for all of the properties.

The problem is that I want to be able to create a simple way of enforcing permissions and doing validation on the client side. It needs to be done on a field by field level.

In javascript I would do this by creating a parallel object structure, which had some sort of

{ permissions : "someLevel", validator : someFunction }
object at the nodes. With empty nodes implying free permissions and universal validation. This would let me simply iterate over the new object and the permissions object, run the check, and deal with the result.

Because I am overfamilar with the hammer that is javascript, this is really the only way that I can see to deal with this problem. My first implementation thus uses reflection to let me treat objects as dictionaries, that can be programatically iterated over, and then I just have dictionaries of dictionaries of PermissionRule objects which can be compared with.

Very javascripty. Very awkward.

Is there some better way that I can do this? Essentially a way to associate a data set with each property, and then iterate over those properties.

Or else am I Doing It Wrong?

It sounds like you are describing custom attributes - ie

[Permissions("someLevel"), Validator("someFunction")]
public string Foo {get;set;}

This requires some reflection to read the attributes, but is quite a nice way of decorating types / members / etc. You might also look at the pre-rolled [PrincipalPermission] for security checks. Is this what you mean?

Note the above would require:

public class PermissionsAttribute : Attribute {
    private readonly string permissions;
    public string Permissions { get {return permissions;}}
    public PermissionsAttribute(string permissions) {
        this.permissions = permissions;
    }
}

(and similar for the other)

You can read them out with Attribute.GetCustomAttributes

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