如何在C#中实现属性和方法? [英] How to implement properties and method in C#?

查看:105
本文介绍了如何在C#中实现属性和方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注释掉了属性及其方法。我如何在接口中实现这些,我也在每个类中注释掉了各个属性。这是来自Begining visual c#2012的UML图。



I have commented out the properties and its method. How do I implement those in the interfaces and I also have commented out individual properties in each class. This is from UML diagram from Begining visual c#2012.

namespace Interfaces
{
    interface IHotDrink
    {
        void Description();

       // string Instance { get; set; }
      //  /int Sugar { get; set; }
        //int AddSugar { get; set; }
        //string Milk { get; set; }
    }
  public class CupOfCoffee: IHotDrink
    { // string BeanType;
        public void Description()
      {
          Console.WriteLine("Hello, what kind of coffee would you like to have?");
      }


    class CupOfTea: IHotDrink
    { // string LeafType;
       public void Description()
        {
            Console.WriteLine("What kind of tea would you like to have?");
        }

    }
    class Program
    {
       static void Main()
        {
            CupOfCoffee C = new CupOfCoffee();
            CupOfTea T = new CupOfTea();

            C.Description();
            T.Description();
        }
    }
}}

推荐答案

无法在接口中实现属性。在界面上定义它。

can't implement properties in interface. define it on interface.
public interface IMyInterface
{
   string Instance 
      {
          get;
          set;
      }
}



然后在实施课程中,你需要实现它




Then in the implementing class, you need to implement it

class MyClass: IMyInterface{
    private string instance ;

    public string Instance {
        get {
            return this.instance;
        }
        set {
            this.instance= value;
        }
    }
}



如果子类的所有属性接口都相同,那么你可以试试 abstract 类如下


if all the property interfaces are same for the sub classes then you can try with abstract class like below

public abstract class MyAbstractClass
{
    public string Instance { get; set; }
    public int Sugar { get; set; }
    public int AddSugar { get; set; }
    public string Milk { get; set; }

    public abstract void Description();
}

public class MyClass : MyAbstractClass
{
    public override void Description()
    {
        Console.WriteLine("Hello, what kind of coffee would you like to have?");
    }
}


您无法在界面内实现任何内容。

界面仅包含方法签名需要在别处实现的属性。



如果要使用需要继承的部分实现的代码,请使用抽象类。
You cannot implement anything inside an interface.
An interface contains only method signatures and properties that need to be implemented elsewhere.

If you want to use a partially implemented code that needs to be inherited, use an abstract class.


这篇关于如何在C#中实现属性和方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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