Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 禁用抽象方法的实现_C# - Fatal编程技术网

C# 禁用抽象方法的实现

C# 禁用抽象方法的实现,c#,C#,下面我有一个代码,它有一个接口、抽象类和一个类。我想在FreeCustomer类中禁用抽象方法Print()的实现。这可能吗?多谢各位 public interface ICustomer { string CustomerName { get; set; } double Amount { get; set; } string Print(); } public abstract class Customer

下面我有一个代码,它有一个接口、抽象类和一个类。我想在FreeCustomer类中禁用抽象方法Print()的实现。这可能吗?多谢各位


    public interface ICustomer
    {
        string CustomerName { get; set; }
        double Amount { get; set; }
        string Print();
    }

    public abstract class Customer : ICustomer
    {
        public string CustomerName { get; set; }
        public double Amount { get; set; }
        public abstract string Print();
    }

    public class GoldCustomer : Customer
    {
        public override string Print() {
            return "You are a Gold Customer: " + CustomerName;
        }
    }

    public class FreeCustomer : Customer 
    {

    }

即使有可能,这也不是一个好主意:为什么你只想执行合同的一部分

您出现此问题的原因似乎是
iccustomer
接口尝试执行太多不同的操作(从而违反了规则)


如果您不总是需要或不想实现
Print
方法,那么将其从接口中取出,或将其移动到单独的接口中。

即使可能,这也不是一个好主意:为什么您只想实现合同的一部分

您出现此问题的原因似乎是
iccustomer
接口尝试执行太多不同的操作(从而违反了规则)


如果您不总是需要或不想实现
Print
方法,则将其从接口中取出,或将其移动到单独的接口中。

在您的特定情况下,不要在基本
Customer
类中将函数声明为
abstract
,而是使用
public virtual
,并在基类中提供一个空的实现


然后,您所要做的就是在实际需要
Print()
功能的类中重写它,而在其他所有方面它都不会做任何事情(因为将使用基本实现)。这意味着您可以将其保留在界面上。

在您的特定情况下,不要在base
Customer
类中将函数声明为
abstract
,而是使用
public virtual
,并在基类中提供empty实现


然后,您所要做的就是在实际需要
Print()
功能的类中重写它,而在其他所有方面它都不会做任何事情(因为将使用基本实现)。这意味着您可以将其保留在接口上。

派生类不需要实现基类的抽象方法的唯一情况是将派生类声明为抽象类

正如MSDN文件所说, 如果基类将成员声明为抽象的,则该方法必须在直接从该类继承的任何非抽象类中重写。如果派生类本身是抽象的,则它继承抽象成员而不实现它们


因此,您可以将FreeCustomer声明为抽象类,然后不需要在其中实现print,尽管我认为它没有任何用途。

派生类不需要实现基类的抽象方法的唯一情况是,您也将派生类声明为抽象类

正如MSDN文件所说, 如果基类将成员声明为抽象的,则该方法必须在直接从该类继承的任何非抽象类中重写。如果派生类本身是抽象的,则它继承抽象成员而不实现它们


因此,您可以将FreeCustomer声明为抽象,然后不需要在其中实现print,尽管我认为它没有任何用途。

print()方法的“实现”在哪里?它不能在接口中,也不能在抽象类中,那么您想禁用什么呢?offtopic为什么您需要抽象类,难道您不能只使用接口吗禁用实现意味着什么?如果您有抽象方法,则必须在派生类期间重写它。FreeCustomer类将强制实现print()方法。我在想,是否可以不在FreeCustomer类中实现print()方法。如果禁用它,当您将
FreeCustomer
实例传递给一个方法,该方法需要
ICCustomer
Customer
并尝试在该实例上调用
print()
时会发生什么?实现在哪里print()方法的名称?它不能在接口中,也不能在抽象类中,那么您想禁用什么呢?offtopic为什么您需要抽象类,难道您不能只使用接口吗禁用实现意味着什么?如果您有抽象方法,则必须在派生类期间重写它。FreeCustomer类将强制实现print()方法。我在想是否可以不在FreeCustomer类中实现print()方法。如果禁用它,当您将一个
FreeCustomer
实例传递给一个需要
ICCustomer
Customer
的方法并尝试在该实例上调用
print()
时会发生什么?我想您是指,不是SRP@dcastro:我写答案时可能不知道ISP。但我认为你是对的,ISP在这里更合适。我认为你指的是网络,而不是网络SRP@dcastro:我写答案时可能不知道ISP。但我认为你是对的,ISP在这里更合适。