C#抽象类返回派生类型枚举 [英] C# abstract class return derived type enumerator

查看:156
本文介绍了C#抽象类返回派生类型枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个抽象类,有没有什么办法可以返回派生类的类型的枚举?或者,我会在基类或泛型方法使用泛型?这里是什么我试图做一个真正的简单化的例子 -

If I have an abstract class, is there any way I can return an enumerator of the derived class's type? Or would I have to use generics in the base class, or a generic method? Here's a really dumbed down example of what I'm trying to do -

public abstract class Person {
    public IEnumerable<MyType> Search() {
        DbDataReader reader = Database.Instance.ExecuteReader(sql);
        while(reader.Read()) {
            MyType row = new MyType();
            row.Load(reader);
            yeild return row;
        }
    }

    private Load(DbDataReader reader) {
        //load instance from reader row
    }

    //declare properties that can be searched, such as Location
}

public class Programmer : Person {
    //declare properties that can be searched, such as Language
}

然后在其他地方,我想可以称之为

Then somewhere else I'd like to be able to call

Programmer programmer = new Programmer();
programmer.Location = "My city";
programmer.Language = "C#";
foreach(Programmer programmer in programmer.Search())
{
    //display list of c# programmers in my city
}

我知道我可以用一个通用的方法做到这一点,如搜索和LT; T>(),但我希望能够从一个不知道准确键入的人(例如,对于一个AJAX处理程序的基类)

I know I can do this with a generic method, like Search<T>(), but I'd like to be able to call the search function from a class that does not know exactly type the Person is (for example, a base class for an AJAX handler)

如果这个不能做,任何人都可以给我一个例子或理由为什么不呢?还是会只是太硬落实到编译器?

If this cannot be done, can anyone give me an example or reason why not? Or would it just be too hard to implement into the compiler?

推荐答案

如果你搜索这个漂亮使用我的方法提出了一种ExtensionMethod。与一个Ext不必定义有效类型的实体的两倍。 programmer.Search<程序员>() => programmer.Search()

If you search an approach with this "pretty" usage I propose an ExtensionMethod. With an Ext you don't have to define the effective type of the Entity twice. programmer.Search<Programmer>() => programmer.Search()

public static PersonExtensions
{
    public static IEnumerable<TType> Search<TType>(this TType row) : where TType : new(), Person 
    {
        DbDataReader reader = Database.Instance.ExecuteReader(sql);
        while(reader.Read()) {
            var row = new TType()
            row.Load(reader);
            yeild return row;
        }
    }
}

这篇关于C#抽象类返回派生类型枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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