Using Statement with Generics: using ISet<> = System.Collections.Generic.ISet<>

前端 未结 6 1696
时光取名叫无心
时光取名叫无心 2020-11-29 09:00

Since I am using two different generic collection namespaces (System.Collections.Generic and Iesi.Collections.Generic), I have conflicts. In other

相关标签:
6条回答
  • 2020-11-29 09:29

    In some cases you can go with inheritance:

    public class MyList<T1, T2> : List<Tuple<IEnumerable<HashSet<T1>>, IComparable<T2>>> { }
    
    public void Meth()
    {
        var x = new MyList<int, bool>();
    }
    
    0 讨论(0)
  • 2020-11-29 09:32

    Your alias name is the same as the class name itself, so you still have ambiguity, just as if you had a using for each namespace. Give the alias of the class a different name, i.e.:

    using FirstNamespace;
    using OtherObject = SecondNamespace.MyObject;
    
    public class Foo
    {
        public void Bar()
        {
            MyObject first = new MyObject;//will be the MyObject from the first namespace
            OtherObject second = new OtherObject;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 09:35

    Unfortunately, the using directive does not do what you want. You can say:

    using Frob = System.String;
    

    and

    using ListOfInts = System.Collections.Generic.List<System.Int32>;
    

    but you cannot say

    using Blob<T> = System.Collections.Generic.List<T>
    

    or

    using Blob = System.Collections.Generic.List
    

    It's a shortcoming of the language that has never been rectified.

    0 讨论(0)
  • 2020-11-29 09:36

    I think you're better off aliasing the namespaces themselves as opposed to the generic types (which I don't think is possible).

    So for instance:

    using S = System.Collections.Generic;
    using I = Iesi.Collections.Generic;
    

    Then for a BCL ISet<int>, for example:

    S.ISet<int> integers = new S.HashSet<int>();
    
    0 讨论(0)
  • 2020-11-29 09:46

    The only way you can alias a generic type is to specialize it as follows.

    using IntSet = System.Collections.Generic.ISet<int>;
    

    You can not alias an open generic type as you have done in your example:

    using MySet = System.Collections.Generic.ISet<>;
    
    0 讨论(0)
  • 2020-11-29 09:49

    You can alias a class doing :

    using Test = NameSpace.MyClass;
    

    Only if the class is NOT generic.

    0 讨论(0)
提交回复
热议问题