在字典中使用对象属性作为键

时间:2010-10-29 10:56:30

标签: .net dictionary lambda

我想使用objects属性作为字典的键。可以这样做吗?

这样做的最终目标是使用它,以便在对象可以处于的各种状态下查看属性是否被锁定。这些锁定值不会持久存在,只存在于模型的业务规则中。

查看字段是否被锁定的理想代码看起来像这样;

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

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

IsFieldLocked是myObject类型的扩展方法。

我希望字典能够存在于myObject中,并且可以根据对象的状态替换为不同的字典变体,例如,已经下了订单或者等待顺序会有不同的字典定义。

希望我能够使用工厂创建不同的字典变体;

Factory.CreateAwaitingOrderLockedFields()

Factory.CreateOrderPlacedLockedFields()

定义字典看起来像这样

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

目标是避免将键作为字符串,强类型键更为理想。

5 个答案:

答案 0 :(得分:4)

我将字典简单地定义为Dictionary<string, bool>

然后扩展方法可能如下所示:

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

答案 1 :(得分:1)

根据herzmeister der welten的建议,这是我的减少解决方案

  public class MyDtoOne : BaseFieldLockingDto<MyDtoOne>
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public MyDtoOne()
        {
            LockedFields = new LockedFields<MyDtoOne>
                               {
                                   { x => x.Age, false }, 
                                   { x => x.Name, true }
                               };
        }
    }

    public class MyDtoTwo : BaseFieldLockingDto<MyDtoTwo>
    {
        public DateTime DateOfBirth { get; set; }

        public MyDtoTwo()
        {
            LockedFields = new LockedFields<MyDtoTwo>
                               {
                                   {x => x.DateOfBirth, false}
                               };
        }
    }

    public class BaseFieldLockingDto<TBaseObject>
    {
        public LockedFields<TBaseObject> LockedFields { get; set; }

        public bool IsFieldLocked<TField>(Expression<Func<TBaseObject, TField>> propertyExpression)
        {
            return LockedFields.IsFieldLocked(propertyExpression);
        }
    }

    public class LockedFields<TBaseObject> : Dictionary<string, bool>
    {
        public void Add<TField>(Expression<Func<TBaseObject, TField>> propertyExpression, bool isLocked)
        {
            Add(GenerateKey(propertyExpression), isLocked);
        }

        private static string GenerateKey<TField>(Expression<Func<TBaseObject, TField>> propertyExpression)
        {
            return GetLambdaPropertyName(propertyExpression);
        }

        public bool IsFieldLocked<TField>(Expression<Func<TBaseObject, TField>> propertyExpression)
        {
            if (Count == 0)
                return false;

            string propertyName = GetLambdaPropertyName(propertyExpression);

            if (ContainsKey(propertyName) == false)
                return false;

            return this[propertyName];
        }

        private static string GetLambdaPropertyName<TField>(Expression<Func<TBaseObject, TField>> propertyExpression)
        {
            var lambda = (LambdaExpression) propertyExpression;
            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression) lambda.Body;
                memberExpression = (MemberExpression) unaryExpression.Operand;
            }
            else
            {
                memberExpression = lambda.Body as MemberExpression;
            }

            if (memberExpression == null)
            {
                throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.",
                                                          propertyExpression));
            }

            return memberExpression.Member.Name;
        }
    }

有了这个我可以做到以下几点;

             private static void Main(string[] args)
    {
        var myDtoOne = new MyDtoOne();

        bool ageLocked = myDtoOne.IsFieldLocked(x => x.Age);
        bool nameLocked = myDtoOne.IsFieldLocked(x => x.Name);


        Console.WriteLine(string.Format("Age locked is {0}", ageLocked ? "true" : "false"));
        Console.WriteLine(string.Format("Name locked is {0}", nameLocked ? "true" : "false"));

        myDtoOne.LockedFields = new LockedFields<MyDtoOne> {{x => x.Age, true}, {x => x.Name, false}};


        bool ageLocked1 = myDtoOne.IsFieldLocked(x => x.Age);
        bool nameLocked1 = myDtoOne.IsFieldLocked(x => x.Name);

        Console.WriteLine(string.Format("Age locked is {0}", ageLocked1 ? "true" : "false"));
        Console.WriteLine(string.Format("Name locked is {0}", nameLocked1 ? "true" : "false"));


        var myDtoTwo = new MyDtoTwo();

        bool dateOfBirth = myDtoTwo.IsFieldLocked(x => x.DateOfBirth);

        Console.WriteLine(string.Format("Date of birth locked is {0}", dateOfBirth ? "true" : "false"));

        myDtoTwo.LockedFields = new LockedFields<MyDtoTwo>() {{x => x.DateOfBirth, true}};

        bool dateOfBirth1 = myDtoTwo.IsFieldLocked(x => x.DateOfBirth);

        Console.WriteLine(string.Format("Date of birth locked is {0}", dateOfBirth1 ? "true" : "false"));

        Console.ReadLine();
    }
}

答案 2 :(得分:0)

我认为你应该只使用继承。创建一个基类LockedField,然后创建继承此类的AwaitingOrderLockedField和OrderPlacedLockedField。

class LockedField {
}

class AwaitingOrderLockedField : LockedField {
}

class OrderPlacedLockedField : LockedField {
}

您的字典将为IDictionary<LockedField, bool>

答案 3 :(得分:0)

您可以使用任何类型声明字典作为键;

Dictionary<Form,bool>

会创建一个字典,其中表单元素用作键。

这是你在哪里问的?

如果要将几个不同的对象用作密钥,则可以使用Dictionary<object,bool>或让所有对象继承自另一个对象Dictionary<masterobject,bool>

答案 4 :(得分:0)

您需要在要用作字典中键的类中实现IComparable接口:

public class MyObject : IComparable {
  public int CompareTo(MyObject obj) {
    // Comparison Logic
  }
}

由于这对于某个对象的成员来说实际上不是一个选项,因此您可以使用Dictionary<string, bool>将字段名称作为键,并在IsFieldLocked()方法中进行一些反映以去除对象来自强类型字段的字符串。