I'm trying to implement a Add Method for Dictionary<TKey,TValue>
which takes a Propert as Parameter.
How I want to initiate the Dictionary:
ExpressionDictionary<string,string> OrigionalValues = new ExpressionDictionary<string,string>();
And I want to Add an item in a Property in code like:
public string Title
{
get { return _title; }
set
{
if (_title != value)
{
_title = value;
OrigionalValues.Add(() => Title,value);
}
}
}
My ExpressionDictionary Class:
public class ExpressionDictionary<T,TValue> : Dictionary<string, TValue>
{
public void Add(Expression<Func<T>> property, TValue value)
{
var body = property.Body as MemberExpression;
if (body != null) Add(body.Member.Name, value);
}
}
So the PropertName is stored as the TKey of the Dictionary as a string. This works when the Property is type of string, but when I try to add a DateTime property and a string Property it hangs up, because it cannot convert, which is clear.
What I'm trying to achive is that I don't need to hardcode the string Name of the Property like
OrigionalValues.Add("Title",value);
How can I design my Add Method or the ExpressionDictionary Class that I can call the Add Method from every Property type I want and the Property Name is stored as TKey? Is this even possible?
这样实例化字典呢?
var OrigionalValues = new ExpressionDictionary<object,object>();
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.