开发者

dynamic in C#, seting property value

开发者 https://www.devze.com 2023-03-06 11:12 出处:网络
I nead to set a property for an object Personi p = new Personi();//this class has a property Datelindja(DateTime)

I nead to set a property for an object

Personi p = new Personi();//this class has a property Datelindja(DateTime)
p.Emri = "Florim";
p.Mbiemri = "Maxhuni";
SetValue(p, "Datelindja", DateTime.Now); //I nead these method. using dynamic keyword
Console.WriteLine(p.Ditelindja);

How do i implement this method that will set the value base on these parameters.

开发者_如何学Go

method signature

SetValue(dynamic orgObj, string property, dynamic value)

Sorry for my bad english.


I don't see why you would need dynamic here.
SetValue will need to use reflection:

void SetValue<TInstance, TValue>(TInstance orgObj, string property, TValue value)
{
    orgObj.GetType().GetProperty(property).SetValue(orgObj, value, null);
}

You could also write this method without generics, because they don't add any benefit in this case:

void SetValue(object orgObj, string property, object value)
{
    orgObj.GetType().GetProperty(property).SetValue(orgObj, value, null);
}


The opensource project Dyamitey has a method Dynamic.InvokeSet that uses DLR plumbing to accomplish that. While in your example you can indeed use reflection since the object itself isn't an IDynamicMetaObjectProvider, but by using Dynamic (dlr) not only will it be more flexible but it will average 3x faster than reflection.

Dynamic.InvokeSet(p,"Datelindja", DateTime.Now)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号