我正在开发一个小型应用程序来掌握C#,并且编写了一个小型应用程序,该应用程序当前将项的值相加(目前已预先定义),以下是我到目前为止所拥有的内容:
//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?
发布于 2016-02-27 08:57:12
使用Interface
public interface IItem
{
string Type { get; }
}然后在类声明上实现接口:
public class Item1 : IItem
{
...
public string Type { get; }
...
}
public class Item2 : IItem
{
...
public string Type { get; }
...
}现在,我们可以将CalcItems()方法定义为接受IItem参数:
public void CalcItems(IItem item, int val)
{
this.Log(item1.Type + "Val:" + val);
this.total += val;
}因此,以下内容现在将引用相同的方法:
Items.CalcItems(new Item1(), 30);
Items.CalcItems(new Item2(), 12);发布于 2016-02-27 08:57:24
向项添加iitem接口,并将Calcitems中的Item1替换为IItem。那么你不需要同时使用calcItems
发布于 2016-02-27 08:57:26
您可以为Item1和Item2定义一个接口,因为它们都共享公共属性Type。
Interfaces (C# Programming Guide)
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);https://stackoverflow.com/questions/35667694
复制相似问题