Is it possible to check a property on a shared object by passing a lambda in the expression to get the parameter?

A simple example: I have a Cat object with the Name property.

I have a class with the PrintName<T>(T objectToPrint)

I can't do Console.WriteLine(objectToPrint.Name) because it is typing T

So, can I pass the parameter as a linq expression that gets the name? Sort of:

 Cat c = new Cat("Bernard the Cat"); PrintName(cat, parameter: c => c.Name); 

Then PrintName can just do

Console.WriteLine(cat.RunLinq(parameter));

+4
source share
3 answers

Well, you can use the interface, but if the property can change, you can do it.

First solution: if you need a property name

 PrintName<T>(T objectToPrint, Expression<Func<T, object>> property) 

Using

 PrintName(cat, c=> c.Name) 

Then, to get the "name" of the property, something like this.

 var name = (property.Body as MemberExpression).Member.Name 

Second solution: if you need a property value

if you want to get the value of the property, use the parameter Func<T, object> func

 // object if you don't know the type of the property, // you can limit it to string if needed, of course PrintName<T>(T objectToPrint, Func<T, object> func) 

Using

 PrintName(cat, c => c.Name) 

then

 var value = func(cat) 
+7
source

This is usually done to pass the type cat using generics:

 void PrintName<T>(T cat, Func<T, string> parameter) { Console.WriteLine(parameter(cat)); } 

A delegate can use the exact type T and therefore access Name . LINQ works so much ( OrderBy , ...). If we replace T with object , this pattern will not work, because this type will not be passed.

+3
source

You can define an interface and implement it on every object that must support printing.

 interface IPrintable { string Name{get;} } class Cat : IPrintable { string Name{get{retrun "Dog";}} } void PrintName(IPrintable objectToPrint) { Console.WriteLine(objectToPrint.Name); } var cat = new Cat(); PrintName(cat); 

You can use reflection or dynamics to implement without implementing an interface.

 void PrintName<T>(T objectToPrint) { dynamic o = (dynamic)objectToPrint; Console.Writeline(o.Name); } 
0
source

Source: https://habr.com/ru/post/1493619/


All Articles