在C#中,当您实现接口时,所有成员都是隐式公共的.那岂不是更好,如果我们可以指定可访问修饰符(protected,internal,除了private当然的),或者我们应该使用抽象类呢?
可能重复:
为什么我不能拥有受保护的接口成员?
作为标题,在C#中.是否有人可能想要受保护或内部接口?
我是OOP的新手并且有一些问题.
为什么接口中声明的方法不能具有修饰符(public,private等).
在这段代码中:
class Program
{
static void Main(string[] args)
{
X ob = new Y();
ob.add(4, 5);
Z ob1 = new Y();
ob1.mull(2, 3);
Console.Read();
}
}
public interface X
{
void add(int x, int y);
}
public interface Z
{
void mull(int x, int y);
}
class Y : X, Z
{
void X.add(int x, int y)//here we are not decalring it as public ,why?
{
Console.WriteLine("sum of X and y is " + (x + y));
} …Run Code Online (Sandbox Code Playgroud) 考虑以下代码行:
ConcurrentDictionary<string, object> error = new ConcurrentDictionary<string, object>();
error.Add("hello", "world"); //actually throws a compiler error
Run Code Online (Sandbox Code Playgroud)
和
IDictionary<string, object> noError = new ConcurrentDictionary<string, object>();
noError.Add("hello", "world");
Run Code Online (Sandbox Code Playgroud)
我最终发现你所要做的就是改变IL以使Add函数变为私有.
现在本着解耦代码的精神,我很可能会使用接口,但似乎并没有找到Concurrent字典的Add方法.
真正使用它是否安全Add(我无法查看IL,因此我不知道它是否真的是线程安全的.)?或者我应该使用具体类型ConcurrentDictionary<TKey, TValue>并明确使用TryAdd.
你什么时候使用其中一个?
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person: IFriendly
{
public abstract string GetFriendly();
}
Run Code Online (Sandbox Code Playgroud)
VS.
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person
{
// some other stuff i would like subclasses to have
}
public abstract class Employee : Person, IFriendly
{
public string GetFriendly()
{
return "friendly";
}
}
Run Code Online (Sandbox Code Playgroud)可能重复:您
是否有理由无法在方法或界面中定义访问修饰符?
你好,
我对接口感到好奇.假设我有以下界面的定义
public interface IPersone
{
string FirstName { get; set; }
string LastName { get; set; }
int CalculateAge(int YearOfBirth);
}
Run Code Online (Sandbox Code Playgroud)
为什么在定义接口的方法和属性前面没有修饰符(public,private,protected)?有什么理由吗?
谢谢你的帮助
我无法意识到接口的受保护方法是如何工作的。我有带有受保护方法的接口和类:Platform - .Net Core 5
public interface ISomeInterface
{
protected void Method_InterfaceRealization()
{
Console.WriteLine("JUST Inside interface realization PROTECTED");
}
protected void Method1();
}
public class SomeClass: ISomeInterface
{
void ISomeInterface.Method1()
{
Console.WriteLine("Method_PROTECTED_NoInterfaceRealization");
}
}
Run Code Online (Sandbox Code Playgroud)