哪有一个属性的getter和一个参数的方法之间的模糊? [英] How can there be ambiguity between a property getter and a method with one argument?

查看:91
本文介绍了哪有一个属性的getter和一个参数的方法之间的模糊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不敢相信,我以前从来没有碰到过这一点,但为什么我得到一个编译器错误此code?

I can't believe I've never come across this before, but why am I getting a compiler error for this code?

public class Main
{
    public Main()
    {
        var ambiguous = new FooBar(1);
        var isConfused = ambiguous.IsValid; // this call is ambiguous
    }
}

public class FooBar
{
    public int DefaultId { get; set; }

    public FooBar(int defaultId)
    {
        DefaultId = defaultId;
    }

    public bool IsValid
    {
        get { return DefaultId == 0; }
    }

    public bool IsValid(int id)
    {
        return (id == 0);
    }
}

下面是错误消息:

FooBar.IsValid和FooBar.IsValid(INT)

Ambiguity between 'FooBar.IsValid' and 'FooBar.IsValid(int)'

这是为什么暧昧?

我想有两个原因不应该是模棱两可:

I'm thinking there are two reasons it should not be ambiguous:

  1. 有后 IsConfused 没有parenthases。
  2. 在没有int参数为 IsConfused
  1. There are no parenthases after IsConfused.
  2. There is no int argument for IsConfused.

在哪里歧义?

推荐答案

有错误的,因为它是模糊的,因为它使用 VAR声明的。它可以是:

There error is because it is ambiguous since it's declared using var. It could be:

bool isConfused = ambiguous.IsValid;

或者

Func<int, bool> isConfused = ambiguous.IsValid;

使用变种需要编译器能够推断出的确切含义,并且在这种情况下,有两种可能性。

Using var requires the compiler to be able to infer the exact meaning, and in this case, there are two possibilities.

不过,如果你删除 VAR ,你还是会得到一个(不同的)错误,因为你不能有两个成员具有相同的名称,一个属性,和一种方法

However, if you remove the var, you'll still get a (different) error, since you can't have two members with the same name, one a property, and one a method.

这篇关于哪有一个属性的getter和一个参数的方法之间的模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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