[英]Pass a property of a class as a parameter?
I need to pass in a property of a class which is used twice in an extension method, to check for duplicate values in this property. 我需要传入一个在扩展方法中使用过两次的类的属性,以检查此属性中的重复值。
public static class MatchedProductsExtensionMethods
{
public static bool IdenticalValues(this List<Product> matchedProducts)
{
var itemToMatch = matchedProducts.First();
if (matchedProducts.All(p => p.PROPERTYTHATCANCHANGE == itemToMatch.PROPERTYTHATCANCHANGE))
return true;
else
return false;
}
}
So I need to be able to pass in the name of a property of the Product
class and then that replaces PROPERTYTHATCANCHANGE
. 因此,我需要能够传递
Product
类的属性的Product
,然后替换PROPERTYTHATCANCHANGE
。 For example, the properties in the Product
class could be ProdName
or ProdUsers
and then I would need to check to see if there are items in the matchedProducts
list which have the same values for these properties. 例如,
Product
类中的属性可以是ProdName
或ProdUsers
,然后我需要检查是否在matchedProducts
列表中是否有这些属性具有相同值的项目。
Thanks in advance! 提前致谢!
To pass in a string property name you're going to have to use reflection, which is not compile-time safe and is relatively slow. 要传递字符串属性名称,您将必须使用反射,这不是编译时安全的,而且相对较慢。 A more type-safe way would be to pass in a delegate instead of a property name:
一种更类型安全的方法是传入一个委托而不是一个属性名:
public static bool IdenticalValues<T>(this List<Product> matchedProducts, Func<Product, T> matchExpression)
{
var itemToMatch = matchedProducts.First();
if (matchedProducts.All(p => EqualityComparer<T>.Default.Equals(matchExpression(p), matchExpression(itemToMatch))))
return true;
else
return false;
}
And call it like this: 并这样称呼它:
bool allMatch = collection.IdenticalValues(i => i.PROPERTYTHATCANCHANGE );
You could even make it completely generic: 您甚至可以使其完全通用:
public static bool IdenticalValues<TEntity, TProperty>(this IEnumerable<TEntity> matchedEntities, Func<TEntity, TProperty> matchExpression)
{
var itemToMatch = matchedEntities.First();
if (matchedEntities.All(p => EqualityComparer<TProperty>.Default.Equals(matchExpression(p), matchExpression(itemToMatch))))
return true;
else
return false;
}
I suggest doing this in a type-safe way: 我建议以类型安全的方式执行此操作:
public static bool IdenticalValues<T>(this List<Product> matchedProducts, Func<Product, T> selector)
{
var itemToMatch = matchedProducts.First();
if (matchedProducts.All(p => selector(p) == selector(p)))
return true;
else
return false;
}
and then calling it like 然后像这样称呼它
matchesProducts.IdenticalValues(p => p.SomeProperty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.