[英]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. 代码库在C#中,基本上我们有大量不同的对象来存储有关不同事物的信息。 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.
如果我将这些对象作为JSON发送到客户端,则很容易以编程方式检查它们以生成所有属性的表单。
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 在javascript中我会通过创建一个并行的对象结构来做到这一点,它有某种形式
{ permissions : "someLevel", validator : someFunction }object at the nodes.
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. 因为我对javascript的锤子过于强大,所以这是我能看到解决这个问题的唯一方法。 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.
因此,我的第一个实现使用反射让我将对象视为字典,可以以编程方式迭代,然后我只有可以与之比较的PermissionRule对象字典的字典。
Very javascripty. 非常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. 这需要一些反思才能读取属性,但这是一种很好的方法来装饰类型/成员/等等。您还可以查看预卷
[PrincipalPermission]
以进行安全检查。 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
您可以使用
Attribute.GetCustomAttributes
读出它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.