在C#中将泛型作为泛型类型参数传递 [英] Passing a generic as generic type parameter in c#

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

问题描述

我在C#中对泛型进行了一些实验,但遇到一个问题,我想将泛型作为具有约束的类型参数传递给实现我不知道其类型的泛型接口.

I did a little experiment on generics in C# and I had a problem where I want to pass a generic type as a type parameter with a constraint to implement a generic interface whose type I don't know.

这是我的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        interface IGenericCollection<T>
        {
            IEnumerable<T> Items { get; set; }
        }

        abstract class GenericCollection<T> : IGenericCollection<T>
        {
            public IEnumerable<T> Items { get; set; }
        }

        //This class holds a generic collection but i have to ensure this class
        //implements my IGenericCollection interface. The problem here is that
        //i dont know which type TGenericCollection is using and so i am unable to
        //pass this information to the constraint. 

        class CollectionOwner<TGenericCollection>
           where TGenericCollection : IGenericCollection< dont know ... >
        {
            protected TGenericCollection theCollection = default(TGenericCollection);
        }

        static void Main(string[] args)
        {
        }
    }
}

我在这里阅读了几篇文章,由于C#和CLR的限制,所有人都告诉我这是不可能的.但是正确的方法是什么?

I have read several posts here, and all told me its impossible due to limitations of C# and CLR. But what would be the right way to do this?

推荐答案

您可以将第二个通用参数添加到实现类中.下面的静态 Example 方法显示了此示例.

You can add the second generic parameter to the implementation class. The static Example method below shows an example of this.

public interface ITest<T>
{
    T GetValue();
}

public class Test<T, U> where T : ITest<U>
{
    public U GetValue(T input)
    {
        return input.GetValue();
    }
}

public class Impl : ITest<string>
{
    public string GetValue()
    {
        return "yay!";
    }

    public static void Example()
    {
        Test<Impl, string> val = new Test<Impl,string>();
        string result = val.GetValue(new Impl());
    }
}

这篇关于在C#中将泛型作为泛型类型参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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