防止在.NET中设置属性

问题描述 投票:1回答:1

我想在创建模型时实施一些访问限制。目前,我的代码看起来像这样。

public Model GetModel()
{
    Model model = new Model();
    if (isAllowedToSet(Field.A))
        model.FieldA = 1;
    if (isAllowedToSet(Field.B))
        model.FieldB = 2;
    if (isAllowedToSet(Field.C))
        model.FieldC = 3;
    return model;
}
private bool isAllowedToSet(Field field)
{
    return (field == Field.A); //Here comes some real logic
}
class Model
{
    public int FieldA { get; set; }
    public int FieldB { get; set; }
    public int FieldC { get; set; }
}

如何更聪明?我当时在考虑使用FieldAttribute,但没有找到解决方案。还是有其他方法?

c# .net custom-attributes
1个回答
0
投票

嗯,是的,您可以使用反射和属性进行此操作

public class Model
{
    [ReadOnly(true)]
    public int FieldA { get; set; }
    public int FieldB { get; set; }
    public int FieldC { get; set; }
}

public Model GetModel()
{
    Model model = new Model();

    if (isAllowedToSet(() => model.FieldA))
        model.FieldA = 1;

    if (isAllowedToSet(() => model.FieldB))
        model.FieldB = 2;

    if (isAllowedToSet(() => model.FieldC))
        model.FieldC = 3;

    return model;
}

private bool isAllowedToSet<T>(Expression<Func<T>> propertyExpression)
{
    var propertyName = ((MemberExpression)propertyExpression.Body).Member.Name;            
    Attribute readonlyAtt = TypeDescriptor.GetProperties(this)[propertyName].Attributes[typeof(ReadOnlyAttribute)];

    return readonlyAtt == null || readonlyAtt.Equals(ReadOnlyAttribute.No);
}

您是否应该完全是另一回事,因为这似乎是对这个问题的解决,它可能有一个更优雅的解决方案,不涉及反射(与其他事物相距很远)。

如果您可以扩大尝试执行此操作的原因,则可能会得到更好的答复。

© www.soinside.com 2019 - 2024. All rights reserved.