簡體   English   中英

C#泛型類型中的“當前類型”占位符?

[英]“Current Type” placeholder in C# generic types?

基本上,我想做的是:

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

...而不必將nextElement強制轉換為XSomething。 有任何想法嗎? 我本來想要某種...

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

先感謝您!

使接口通用:

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

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

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

好吧,您可以使用隱式運算符來做到這一點(盡管我不是100%確信在這種情況下它會工作):

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

但是請注意,這顯然不是一個好主意。 最干凈的方法是進行顯式轉換。

我建議使接口通用,以便屬性的類型可以是接口的通用類型。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM