在接口中创建通用属性

cas*_*out 4 .net c# asp.net

我想用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
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jep*_*sen 7

按照其他答案的建议将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();
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)


Ed *_*d W 6

你几乎就在那里,只需使用定义你的界面 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

甚至可以使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)