簡體   English   中英

在接口中創建通用屬性

[英]Create generic property in interface

我想用GetId()方法創建一個接口。 根據子項,它可以是int,string或其他東西。 這就是為什么我嘗試使用返回類型對象(但后來我不能在子項中指定類型)並想嘗試使用泛型。

我怎樣才能做到這一點?

我已經擁有的東西:

public interface INode : IEquatable<INode>
{
   object GetId();
}

public class PersonNode : INode
{
   object GetId(); //can be int, string or something else
}

public class WorkItemNode : INode
{
   int GetId(); //is always int
}

謝謝!

你幾乎就在那里,只需使用INode<T>定義你的界面

public interface INode<T> : IEquatable<INode<T>>
{
    T GetId();
}

public class PersonNode : INode<string>
{
    public bool Equals(INode<string> other)
    {
        throw new NotImplementedException();
    }

    public string GetId()
    {
        throw new NotImplementedException();
    }
}

public class WorkItemNode : INode<int>
{
    public int GetId()
    {
        throw new NotImplementedException();
    }

    public bool Equals(INode<int> other)
    {
        throw new NotImplementedException();
    }
}

甚至可以使用帶有界面的object

public class OtherItemNode : INode<object>
{
    public bool Equals(INode<object> other)
    {
        throw new NotImplementedException();
    }

    public int Id { get; set; }

    public object GetId()
    {
        return Id;
    }
}

這應該做:

public interface INode<T> : IEquatable<INode<T>>
{
   T GetId();
}

BTW:GetId()是一種方法。

一個屬性看起來像這樣:

public interface INode<T> : IEquatable<INode<T>>
{
    T Id
    {
        get;
        set;
    }
}

根據其他答案的建議,將INode接口更改為泛型類型interface INode<out T>

或者,如果您不想這樣做,請明確實現非通用接口,並提供類型安全的公共方法:

public class WorkItemNode : INode
{
    public int GetId() //is always int
    {
        ...
        // return the int
    }

    object INode.GetId()  //explicit implementation
    {
        return GetId();
    }

    ...
}

您的INode接口實際上可能是INode<T> ,其中T是int,string,等等? 然后你的財產可以是T型。

如果你需要繼承,那么你有INode<T>INode接口,其中INode<T>具有特定於類型的東西,而INode具有非類型特定的東西(以及用於Id檢索的基於對象的屬性或方法)

他![重新是這種情況的解決方案使用默認的int類型,你需要使用PersonNode T作為泛型類型而WorkItemNode使用int而不是T作為類的默認泛型類型聲明

暫無
暫無

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

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