首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代码重构C#

代码重构C#
EN

Stack Overflow用户
提问于 2016-02-27 08:51:47
回答 5查看 125关注 0票数 0

我正在开发一个小型应用程序来掌握C#,并且编写了一个小型应用程序,该应用程序当前将项的值相加(目前已预先定义),以下是我到目前为止所拥有的内容:

代码语言:javascript
复制
//Defining classes
 public class Item1{
  public string Type{get{return "Item1";}}
 }
 public class Item2{
  public string Type{get{return "Item2";}}
 }

//Methods
public void CalcItems(Item1 item1, int val){
 this.Log(item1.Type + "Val:" + val);
 this.total += val;
}

public void CalcItems(Item2 item2, int val){
 this.Log(item2.Type + "Val:" + val);
 this.total += val;
}

//Calling these methods
Items.CalcItems(new Item1(), 30);
Items.CalcItems(new Item2(), 12);

如何通过一个calc方法同时传递Item1和Item 2?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-02-27 08:57:12

使用Interface

代码语言:javascript
复制
public interface IItem
{
    string Type { get; }
}

然后在类声明上实现接口:

代码语言:javascript
复制
public class Item1 : IItem
{
    ...
    public string Type { get; }
    ...
}

public class Item2 : IItem
{
    ...
    public string Type { get; }
    ...
}

现在,我们可以将CalcItems()方法定义为接受IItem参数:

代码语言:javascript
复制
public void CalcItems(IItem item, int val)
{
    this.Log(item1.Type + "Val:" + val);
    this.total += val;
}

因此,以下内容现在将引用相同的方法:

代码语言:javascript
复制
Items.CalcItems(new Item1(), 30);
Items.CalcItems(new Item2(), 12);
票数 1
EN

Stack Overflow用户

发布于 2016-02-27 08:57:24

向项添加iitem接口,并将Calcitems中的Item1替换为IItem。那么你不需要同时使用calcItems

票数 1
EN

Stack Overflow用户

发布于 2016-02-27 08:57:26

您可以为Item1Item2定义一个接口,因为它们都共享公共属性Type

Interfaces (C# Programming Guide)

代码语言:javascript
复制
public interface IMyItem
{
    string Type;
}

public class Item1 : IMyItem
{
    public string Type{get{return "Item1";}}
}
public class Item2: IMyItem
{
    public string Type{get{return "Item2";}}
}

public void CalcItems(IMyItem item, int val){
    this.Log(item.Type + "Val:" + val);
    this.total += val;
}

Items.CalcItems(new Item1(), 30);
Items.CalcItems(new Item2(), 12);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35667694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档