使用对象属性在字典中的关键字典、属性、对象、关键

2023-09-03 17:22:05 作者:枯涩 Feelings

我想用一个对象属性作为键的字典。可以这样做?

I would like to use an objects property as the key for a dictionary. Can this be done?

这样做的最终目的是要利用这个所以可以看到,如果财产被锁定与否,在各种状态下,一个对象可以在这些锁定的值不保留,只存在于该型号的业务规则。

The ultimate goal for this is to use this so can see if the property is locked or not, in various states that an object can be in. These locked value is not persisted, just exist in the business rules for the model.

理想code,看是否字段被锁定是这样的;

Ideal code to see if field is locked would look like this;

bool ageLocked = myObject.IsFieldLocked( x => x.Age);

bool nameLocked = myObject.IsFieldLocked(x => x.Name);

IsFieldLocked正在为myObject的类型的扩展方法。

IsFieldLocked being an extension method for the type of myObject.

我想字典住在myObject的和可更换的与基于对象的状态不同词典的变化,例如,已经下了订单,或等待秩序将有不同的字典定义。

I would like the dictionary to live in myObject and be replaceable with different dictionary variations based on the state of the object, for example, has placed an order or awaiting order would have different dictionary definitions.

希望我将能够使用一个工厂来创建不同的字典中的变化;

Hopefully I would be able to use a factory to create the different dictionary variations;

Factory.CreateAwaitingOrderLockedFields()

Factory.CreateOrderPlacedLockedFields()

定义字典看起来像这样

Defining the dictionary looking something like this

new Dictionary< ***MissingMagic***, bool>()
{
  { x => x.Age , true},
  { x => x.Name, false}
}

目的是避免键为一个字符串,强烈地受到远更期望的输入键。

Aim is to avoid the key being a string, strongly typed key by far more desirable.

推荐答案

我定义词典只是作为一个词典&LT;字符串,布尔&GT;

I'd define the dictionary simply as a Dictionary<string, bool>.

扩展方法,那么可能看起来是这样的:

The extension method then could look something like this:

public static bool IsFieldLocked<TField>(this MyClass self, Expression<Func<MyClass, TField>> propertyExpression)
{
    // note: null checks etc omitted for brevity

    var lambda = (LambdaExpression)propertyExpression;
    MemberExpression memberExpression;
    if (lambda.Body is UnaryExpression)
    {
        var unaryExpression = (UnaryExpression)lambda.Body;
        memberExpression = (MemberExpression)unaryExpression.Operand;
    }
    else
    {
        memberExpression = (MemberExpression)lambda.Body;
    }

    string propertyName = memberExpression.Member.Name;

    return self.InternalLockedFieldsDictionary[propertyName];
}