gpt4 book ai didi

c# - 接口(interface)中的公共(public)变量?

转载 作者:行者123 更新时间:2023-11-30 14:12:43 26 4
gpt4 key购买 nike

我正在阅读 this , 并注意到问题中的第二点:

An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.

我阅读了答案,但似乎没有一个能澄清这一点,除了:

For .Net,

Your answer to The second interviewer is also the answer to the first one... Abstract classes can have implementation, AND state, interfaces cannot...

我认为面试官的回答是正确的,因为界面中不能有任何变量。我在这里有点困惑。有人可以澄清吗?我的问题是,为什么面试官会问这么奇怪(?)的问题?

最佳答案

所有接口(interface)成员都是隐式公开,这就是为什么您不能在接口(interface)中为属性或方法设置public

interface C# - MSDN

Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.

针对您的问题:

I think the answer to the interviewer was correct, as you cant have any variables inside the interface.

没有。您可以在界面中定义属性。像这样的东西:

interface ITest
{
int MyProperty { get; set; }
}

public class TestClass : ITest
{
public int MyProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}

编辑:

An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class?

可能面试官想看看你是否会说默认情况下接口(interface)中的所有成员都是公共(public)的,而在抽象类中你可以有私有(private)、 protected 、公共(public)成员等。

关于c# - 接口(interface)中的公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com