什么会导致接口上的 属性 获取失败?

What would cause a property get on an interface to fail?

我有一个带有 属性 的接口,以及一个实现该接口的 class。我将 class 的实例投射到接口,然后尝试读取 属性 并且它没有检索值。谁能看出为什么?

接口:

public interface IFoo
{
    int ObjectId { get; }
}

Class:

public class Bar : IFoo
{
     public int ObjectId { get; set; }
}

用法:

...
Bar myBar = new Bar() { ObjectId = 5 };
IFoo myFoo = myBar as IFoo;
int myId = myFoo.ObjectId;  //Value of myFoo.ObjectId is 5 in Watch, but myId remains at 0 after statement
...

这过于简单化了,但本质上就是我正在做的事情。为什么在watchwindow中可以看到myFoo.ObjectId的值,但是对myId赋值失败(赋值前后均为0)?

您可能通过手动干预或更改值的语句操纵了手表上的数据。

我在控制台应用程序中对您的代码进行了快速测试,myId 的值为 5。

class Program
{
    static void Main(string[] args)
    {
        Bar myBar = new Bar() { ObjectId = 5 };
        IFoo myFoo = myBar as IFoo;
        int myId = myFoo.ObjectId;

        Console.WriteLine(myId); // 5

        Console.ReadLine();
    }
}

interface IFoo
{
    int ObjectId { get; }
}

class Bar : IFoo
{
    public int ObjectId { get; set; }
}