为什么我不能覆盖,并在同一时间新一属性(C#)? [英] Why can't I override and new a Property (C#) at the same time?

查看:132
本文介绍了为什么我不能覆盖,并在同一时间新一属性(C#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据的 这个问题 的好像你可以为方法做到这一点。我想知道的是为什么当我的属性尝试它不起作用。

 公共类Foo 
{
公共虚拟对象的值
{
获得;
组;
}
}

公共类Foo< T> :富
{
公众覆盖对象的值
{
得到
{
返回base.Value;
}

{
base.Value =(T)值; //注上套类型检查
}
}

公开新的T值
{
{返回(T)base.Value; }
集合{base.Value =价值; }
}
}



错误从C#4.0 RC1的消息




错误1类型
'ClassLibrary1.Foo'已经
包含了'价值'
ClassLibrary1\定义31的Class1.cs 22
ClassLibrary1的



解决方案

您不能有两个属性使用相同的名称。这不是在C#允许。唯一的例外是索引,因为在索引器的情况下,由索引类型签名的变化。



您不能使一个过载的方法,只有在返回类型不同。用一个名称的属性基本上是相同的规则禁止的,因为它在内部是一对不带参数的get访问方法。


According to this question it seems like you can do this for Methods. What I want to know is why it doesn't work when I try it with properties.

public class Foo
{
    public virtual object Value
    {
        get;
        set;
    }
}

public class Foo<T> : Foo
{
    public override object Value
    {
        get
        {
            return base.Value;
        }
        set
        {
            base.Value = (T)value; //inject type-checking on sets
        }
    }

    public new T Value
    {
        get { return (T)base.Value; }
        set { base.Value = value; }
    }
}

Error message from C# 4.0 RC1

Error 1 The type 'ClassLibrary1.Foo' already contains a definition for 'Value' ClassLibrary1\Class1.cs 31 22 ClassLibrary1

解决方案

You can't have two properties using the same name. This is not allowed in C#. The only exception to this is indexers, since, in the case of an indexer, the signature changes by the index type.

You cannot make an overload for a method that only differs by the return type. A property with a single name is basically prohibited by the same rule, since it is internally a pair of methods with no argument for the get accessor.

这篇关于为什么我不能覆盖,并在同一时间新一属性(C#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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