c# - 用于检查重复项(不同对象、不同字段)的通用 C# 函数
问题描述
我想创建一个通用函数,它获取三个参数(对象列表、属性名称和值)......该函数必须检查重复项。所以 :
class A {
public string description;
public string abbreviation;
}
class B {
public string description;
public string name;
}
我有两个 List 对象...一个具有多个 A 类对象,一个具有多个 B 类对象。
List <A> listOfA
List <B> listOfB
我想要一个这样的函数:
bool hasDuplicateAbbreviation = CheckDuplicate (listOfA, "abbreviation", "ALG");
bool hasDuplicateName = CheckDuplicate (listOfB, "name", "Mrs. Smith");
bool hasDuplicateDescription = CheckDuplicate (listOfB, "description", "Nice toolkit");
我该怎么做?
如果相同的函数也可以用于具有整数等级的 C 类,那就太好了:
class C {
public string description;
public int rank;
}
List <C> listOfC
bool hasDuplicateRank = CheckDuplicate (listOfC, "rank", 2);
解决方案
您需要使用反射(需要导入System.Reflection
):
public static int CheckDuplicate<T>(IEnumerable<T> input, string field, object value)
{
int count = 0;
Type type = typeof(T);
foreach(var item in input)
{
var fieldInfo = type.GetField(field);
if(fieldInfo!= null)
if(fieldInfo.GetValue(item) == value) count++;
else
{
var propInfo = type.GetProperty(field);
if(propInfo != null && propInfo.GetValue(item) == value) count++;
}
}
return count;
}
这将返回给定值重复的次数。
if(CheckDuplicate(a, "abbreviation", "abbr1") > 1)
{
// there is a duplicate
}
推荐阅读
- grafana - 可视化所有标签值
- javascript - 如何从本地存储中删除搜索栏过去的搜索?
- c++ - 是否可以在编译时强制两个派生类总是为覆盖函数返回不同的值?
- spring - 覆盖 KafkaAutoConfiguration 时出错
- bash - 用于 Windows 的 ubuntu 上的 Mosquitto mqtt
- c# - FluentValidation 使用 DB 检查重复值
- python - 循环遍历 Numpy ndarray 的所有样本
- ios - Xcode 函数中数组的 EXC_BAD_ACCESS
- powershell - 为什么`[SomeType] | Get-Member -Static 返回“SomeType”的静态成员而不是“System.RuntimeType”的静态成员?
- php - 使用 PHPMailer 形成表单