在协变接口上设置属性 [英] Set Property on a Covariant Interface

查看:83
本文介绍了在协变接口上设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下协变接口:

public interface IHierarchical<out T> where T : IHierarchical<T> {
    T Parent { get; }
    IEnumerable<T> Children { get; }
}

然后我从上面的接口派生出以下接口:

I then have the following interfaces which derive from the interface above:

public interface ISiteMapNode<T> : ISiteMapNode where T : ISiteMapNode<T> { }

public interface ISiteMapNode : IHierarchical<ISiteMapNode> {
    string Name { get; set; }
}

最后我有以下实现:

public class SiteMapNode : ISiteMapNode<SiteMapNode> {
    public string Name { get; set; }
    public ISiteMapNode Parent { get; }
    public IEnumerable<ISiteMapNode> Children { get; }
}

现在我有一个方法接受ISiteMapNode类型的参数,并尝试设置Parent属性。显然,这是不起作用的,因为Parent属性是只读的。我必须删除集合以使IHierachical接口协变。有什么办法可以做到?

Now I have a method which takes an argument of type ISiteMapNode and tries to set the Parent property. Obviously this won't work as the Parent property is readonly. I had to remove set to make the IHierachical interface covariant. Is there any way I can do this?

推荐答案

不行。

您可以在类型参数之前想到 out 关键字,它表示声明的接口将仅返回(或 output )值。指定的类型。这类似于 in 关键字,它表示声明的接口将只接受指定类型的值作为 input

You can think of the out keyword before a type argument as saying that the declared interface will only return (or output) values of the specified type. This is analogous to the in keyword saying that the declared interface will only accept values of the specified type as input.

=值仅出

in =值仅输入

out = values are ONLY going out
in = values are ONLY going in

协变量类型参数:

interface IHierarchical<out T>
{
    T Parent
    {
        get; // OK -- it's going out
        set; // ERROR
    }
}

协变量类型参数:

interface IHierarchical<in T> 
{
    T Parent
    {
        get; // ERROR
        set; // OK -- it's going in
    }
}

不变类型参数:(正常)

Invariant type parameter: (normal)

interface IHierarchical<T> 
{
    T Parent
    {
        get; // OK
        set; // OK
    }
}

另一种方法是拆分接口分为协变和逆变子接口。像这样的事情:

One alternative could be to split the interface into a covariant and a contravariant subinterface. Something like this:

interface IHierarchical<T> : IHierarchicalIn<T>, IHierarchicalOut<T>
{
}

interface IHierarchicalIn<in T>
{
    T Parent { set; }
}

interface IHierarchicalOut<out T>
{
    T Parent { get; }
}

class Node : IHierarchical<Node>
{
    public Node Parent
    {
        get { throw new NotImplementedException(); }
        set { throw new NotImplementedException(); }
    }
}

我真的看不到有什么用不过。

I don't really see a use for that though.

这篇关于在协变接口上设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆