泛型的C#问题 [英] C# Problem with Generics

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

问题描述

我有什么?

我有一个抽象类QueryExecutor和派生类SqlQueryExecutor,如下所示.

I have an abstract class, QueryExecutor and derived class, SqlQueryExecutor shown below.

abstract class QueryExecutor<T>
{
    public abstract T Execute();
}

class SqlQueryExecutor<T> : QueryExecutor<T> where T:ICollection
{
    public override T Execute()
    {
        Type type = typeof(T);

        // Do common stuff
        if (type == typeof(ProfileNodeCollection))
        {
            ProfileNodeCollection nodes = new ProfileNodeCollection();
            // Logic to build nodes
            return (T)nodes;
        }
        else
        {
            TreeNodeCollection nodes = new TreeNodeCollection();
            Logic to build nodes

            return (T)nodes;                
        }
    }
}

我想做什么?

Execute()方法的实现中,我想构造适当的ICollection对象并返回它.

In the implementation of Execute() method, I want to construct the appropriate ICollection object and return it.

我遇到什么问题?

Execute()方法中,return (T)nodes;行显示以下编译时错误:

In Execute() method, the line, return (T)nodes; shows the following compile time error:

无法将类型"WebAppTest.ProfileNodeCollection"转换为"T"

Cannot convert type 'WebAppTest.ProfileNodeCollection' to 'T'

有什么主意我该如何解决?

Any idea how can I solve this?

提前谢谢!

推荐答案

好吧,一种简单的解决方法是让编译器 less 知道正在发生的事情,这样它就可以只需将其交给CLR:

Well, a simple way of fixing it is to just make the compiler less aware of what's going on, so that it'll just defer it to the CLR:

return (T)(object)nodes;

您可以将其放在单个位置,并在分配时使用隐式转换为object:

You could put this in a single place and use an implicit conversion to object on assignment:

object ret;
// Do common stuff
if (type == typeof(ProfileNodeCollection))
{
    ProfileNodeCollection nodes = new ProfileNodeCollection();
    // Logic to build nodes
    ret = nodes;
}
else
{
    TreeNodeCollection nodes = new TreeNodeCollection();
    Logic to build nodes

    ret = nodes;
}
return (T)ret;

这不是很令人愉快,但应该可以.不过,最好为不同的集合类型创建单独的派生类-将通用代码放在抽象基类中.

It's not terribly pleasant, but it should work. It would probably be nicer to create separate derived classes for different collection types though - possibly putting common code in an abstract base class.

这篇关于泛型的C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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