代码之家  ›  专栏  ›  技术社区  ›  Michael

C泛型类型中的“当前类型”占位符?

  •  1
  • Michael  · 技术社区  · 15 年前

    基本上,我想做的是:

    public class MySpecialCollection<T>
        where T : ISomething { ... }
    
    public interface ISomething
    {
        public ISomething NextElement { get; }
        public ISomething PreviousElement { get; }
    }
    
    public class XSomething : ISomething { ... }
    
    MySpecialCollection<XSomething> coll;
    XSomething element = coll.GetElementByShoeSize(39);
    XSomething nextElement = element.NextElement; // <-- line of interest
    

    …无需将nexteement转换为xsometing。有什么想法吗? 我本来想要一种…

    public interface ISomething
    {
        public SameType NextElement { get; }
        public SameType PreviousElement { get; }
    }
    

    提前谢谢!

    3 回复  |  直到 15 年前
        1
  •  10
  •   Guffa    15 年前

    使接口通用:

    public class MySpecialCollection<T> where T : ISomething<T> {
      ...
    }
    
    public interface ISomething<T> {
      T NextElement { get; }
      T PreviousElement { get; }
    }
    
    public class XSomething : ISomething<XSomething> {
      ...
    }
    
        2
  •  1
  •   ShdNx    15 年前

    好吧,您可以使用隐式运算符(尽管我不能100%确定它在这种情况下会起作用):

    public static XSomething operator implicit(ISomething sth)
    {
         return (XSomething)sth;
    }
    

    但请注意,这显然不是一个好主意;最干净的方法是进行显式转换。

        3
  •  1
  •   James Manning    15 年前

    我建议将接口设为泛型,以便属性的类型可以是接口的泛型类型。

    using System;
    
    namespace ConsoleApplication21
    {
        public interface INextPrevious<out TElement>
        {
            TElement NextElement { get; }
            TElement PreviousElement { get; }
        }
    
        public class XSomething : INextPrevious<XSomething>
        {
            public XSomething NextElement
            {
                get { throw new NotImplementedException(); }
            }
    
            public XSomething PreviousElement
            {
                get { throw new NotImplementedException(); }
            }
        }
    
        public class MySpecialCollection<T>
            where T : INextPrevious<T>
        {
            public T GetElementByShoeSize(int shoeSize)
            {
                throw new NotImplementedException();
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var coll = new MySpecialCollection<XSomething>();
                XSomething element = coll.GetElementByShoeSize(39);
                XSomething nextElement = element.NextElement;
            }
        }
    }