开发者

"Current Type" placeholder in C# generic types?

Basically, what I want to do, is:

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

... without having to cast nextElement to XSomething. Any ideas? I would have wanted something in the kind of ...

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

Thank you in advance!


Make the interface generic:

public class MySpecialCollection<T> where T : ISomething<T> {
  ...
}

public interface ISomething<T> {
  T NextElement { get; }
  T PreviousElement { get; }
}

public class XSomething : ISomething<XSomething> {
  ...
}


Well, you can do it using an implicit operator (though I'm not 100% sure it will work in this case):

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

But note that this is clearly not a very good idea; the cleanest way is to do an explicit cast.


I'd recommend making the interface generic so the types of the properties can be the interface's generic type.

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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜