使用泛型的扩展方法编译器错误CS0311

时间:2017-05-19 07:12:26

标签: c# generics

我想用泛型创建扩展方法。但是当使用这种方法时,我得到错误编译器错误CS0311。我怎么解决这个问题?这是一个例子。

using Compare;
using System.Collections.ObjectModel;

static class Program
{
    static void Main()
    {
        var OldItemListe = new LoadListe();
        var NewItemListe = new LoadListe();
        bool ReturnValue = new Import().Compare(OldItemListe, NewItemListe);  //Here I got the Error CS0311
    }
}

namespace Compare
{
    /// <summary>Baseclass for all Elements </summary>
    public class BaseClass
    {
        /// <summary> Elementname </summary>
        public string Name { get; set; }
        /// <summary> Beschreibung </summary>
        public string Description { get; set; }
    }
    public abstract class BaseListe<T> : Collection<T> where T : BaseClass, new() { }
    public class Load : BaseClass{}
    public sealed class LoadListe : BaseListe<Load> {}


    public class Import
    {
        public bool Compare<U>(U OldItemListe, U NewItemListe) where U : BaseListe<BaseClass>
        {
            // do something
            if (OldItemListe[1].Name == NewItemListe[1].Name) return true; // only Example
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这很可能会产生其他待解决的问题,但你可以做一些事情:

public class GBase
{
    public string Name { get; set; }
}

public class GLevel1 : GBase
{

}

public class GLevel2 : GBase
{

}


public class CollectionBase<T> : Collection<T> where T : GBase
{ }

public class CollectionLevel0 : CollectionBase<GBase>
{

}

public class CollectionLevel1 : CollectionLevel0
{

}

public class Comparer
{
    public bool Compare<T>(T old, T newer) where T : CollectionLevel0
    {
        return old[0].Name == newer[0].Name;
    }
}

然后您可以像:

一样使用它
var col1 = new CollectionLevel0();
var col2 = new CollectionLevel0();
col1.Add(new GLevel1() { Name = "Dave" });
col2.Add(new GLevel2() { Name = "Bob" });

var col3 = new CollectionLevel1();
col3.Add(new GLevel1() { Name = "Billy" });
var col4 = new CollectionLevel1();
col4.Add(new GLevel1() { Name = "Billy" });

Comparer a = new Comparer();
bool b1 = a.Compare<CollectionLevel0>(col1, col2);
bool b2 = a.Compare<CollectionLevel1>(col3, col4);