编写某个泛型方法

本文关键字:泛型方法 | 更新日期: 2023-09-27 18:18:19

我有一系列的方法要写,但我认为有一些共性(好吧,我知道有)。我想要看到的方法将接受两个东西,一个对象和…嗯,第二个我不太确定,但可能是一个字符串。

对象应该是泛型的,尽管它只能来自一个集合列表(在这种情况下,通用性似乎是它们同时继承了INotifyPropertyChanging和INotifyPropertyChanged接口)。

字符串应该是泛型对象内的属性名。在投入使用之前,应该检查该属性是否存在于该对象中(它将被用作根据给定属性比较对象的一种方法)。

所以我猜这个过程会是…泛型对象被传递到方法中(连同属性名称字符串)。检查对象是否包含该属性。如果是,继续并以某种方式访问'object '。如果'PropertyName'是提供的字符串,

我不知道这是否容易,是否可能,甚至是否明智,但我知道这会节省我一些时间。

事先感谢您可能就此提供的任何建议。

编辑:感谢大家到目前为止的所有回复。让我澄清一些事情:

"access"的说明

当我说:"……并以某种方式访问object。PropertyName " "我的意思是这个方法应该能够使用那个属性名就好像它只是那个对象的一个属性。所以,让我们说传入的字符串是"ClientName",将有能力读(可能写,虽然目前我不这样认为,因为它只是一个检查)对象。

我想做什么

我有一个使用Linq访问SQL数据库的WCF服务。我所说的对象是从程序SQLMetal.exe生成的实体,所以我的对象是"客户端"、"用户"之类的东西。我写了一个方法,它接受一个实体列表。此方法仅添加集合中不存在的实体(有些可能是重复的)。它通过检查实体中的属性(对应于数据库列中的数据)来确定哪些是重复的。这个属性可能是可变的

编写某个泛型方法

听起来好像你并不想检查它是否是某种类型,如果是这样的话,你就不需要检查,实际上不检查类型更容易。这显示了如何检查属性是否存在,它是否可读可写,并显示了如何在找到它后使用它:

private void Form1_Load(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();
    PropertyInfo info = GetProperty(sb, "Capacity");
    //To get the value of the property, call GetValue on the PropertyInfo with the object and null parameters:
    info.GetValue(sb, null);
    //To set the value of the property, call SetValue on the PropertyInfo with the object, value, and null parameters:
    info.SetValue(sb, 20, null);
}
private PropertyInfo GetProperty(object obj, string property)
{
    PropertyInfo info = obj.GetType().GetProperty(property);
    if (info != null && info.CanRead && info.CanWrite)
        return info;
    return null;
}

我认为在c#中只有索引器属性可以接受参数。我相信,如果你在VB中编写带有参数的属性,并试图在c#中引用该程序集,它们将显示为方法而不是属性。

你也可以写一个这样的函数,它将接受两个对象和一个字符串作为属性名,并返回匹配的结果:

private bool DoObjectsMatch(object obj1, object obj2, string propetyName)
{
    PropertyInfo info1 = obj1.GetType().GetProperty(propertyName);
    PropertyInfo info2 = obj2.GetType().GetProperty(propertyName);
    if (info1 != null && info1.CanRead && info2 != null && info2.CanRead)
        return info1.GetValue(obj1, null).ToString() == info2.GetValue(obj2, null).ToString();
    return false;
}

比较属性的值可能比较棘手,因为它将它们作为对象进行比较,谁知道如何处理它们的相等性。但是在这种情况下,将值转换为字符串应该可以工作。

如果你知道两个对象是相同的类型,那么你可以简化它:

private bool DoObjectsMatch(object obj1, object obj2, string propetyName)
{
    PropertyInfo info = obj1.GetType().GetProperty(propertyName);
    if (info != null && info.CanRead)
        return info.GetValue(obj1, null).ToString() == info.GetValue(obj2, null).ToString();
    return false;
}

我想你在找这样的东西:

public void SomeMethod<T>(T object, string propName) 
    where T : INotifyPropertyChanging, INotifyPropertyChanged
(
    var type = typeof(T);
    var property = type.GetProperty(propName);
    if(property == null)
        throw new ArgumentException("Property doesn't exist", "propName");
    var value = property.GetValue(object, null);
)