访问泛型方法里面对象的属性 [英] Accessing object's property inside generic method

查看:508
本文介绍了访问泛型方法里面对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问泛型方法内的对象的属性结果
我不能使用,其中T:A ,因为这种方法会收到不同对象,但是所有的对象都有一个共同的特性去努力。结果
(我也不能为他们的通用接口)

How can access the property of an object inside generic method?
I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.
(I also can't make for them a common interface)

public class A
{
    public int Number {get;set;}
}


List<A> listA = new List<A>{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work<A>(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}



更新:我也需要设置的属性

An update: I need also to set the property

推荐答案

您有几种选择:


  • 请提供通用接口。

  • 使用反射。

  • 在.NET 4中使用的动态类型。

我知道你说你不能做第一,但它的性能和可维护性最好的选择,所以请重新考虑,如果可能选择其他方法之前。请记住,即使你不能修改原始代码,您可能仍然能够选择第一个选项。例如,如果你的类是局部类可以实现在另一个文件中的接口:

I know you said you can't do the first, but it's the best option for performance and maintainability so please reconsider if its possible before choosing one of the other methods. Remember that even if you can't modify the original code you might still be able to choose the first option. For example if your classes are partial classes you can implement the interface in another file:

文件1:

// Automatically generated code that you can't change.
partial class A
{
    public int Number { get; set; }
}



文件2:

File 2:

interface IHasNumber
{
    int Number { get; set; }
}

partial class A : IHasNumber
{
}

如果原来的类没有被定义为局部的,你可以写他们周围实现接口的包装类。

If the original class isn't defined as partial you could write wrapper classes around them that implement the interface.

一旦你拥有了共同的接口你可以改变你的通用的限制,要求该接口:

Once you have the common interface you can change your generic constraint to require this interface:

where T : IHasNumber

这篇关于访问泛型方法里面对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆