2016-02-27 85 views
0

我工作的一个小应用程序来获得与C#中的交手,我已经写了一个小程序,目前加起来的项目(目前预定义)这里的值是我到目前为止有:代码重构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); 

如何通过一种计算方法传递Item1和Item 2?

+0

“group”是什么意思?你是否希望'Item1'和'Item2'被传递给相同的'CalcItems'方法? – Jamiec

+0

@Jamiec是的,通过这两个项目通过相同的方法。对不起找不到措辞哈哈 – John

回答

2

使用Interface

public interface IItem 
{ 
    string Type { get; } 
} 

然后实现你的类声明的接口:

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

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

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

现在我们可以接受的IItem参数定义方法CalcItems()

这样下面现在将引用同样的方法:

Items.CalcItems(new Item1(), 30); 
Items.CalcItems(new Item2(), 12); 
+0

我怎么能实现这个与所有类,你可以看到在问题是在单独的文件。 – John

+0

你可以在你的类定义上实现'IItems'。如果您无法访问源代码,请继承您正在使用的类来实现接口。 (例如,'公共类MyItem1:Item1,IItem'将是一个可能的类声明)。 – Lemonseed

+0

完美!对于我在C#编程中可能遇到的任何阅读材料,您有任何建议吗?因为我的知识不如其他语言的知识。谢谢 – John

1

的的iItem接口添加到您的项目,并在Calcitems用的iItem更换项目1。然后你不需要两个calcItems

1

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

MSDN: 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); 
0

你可以利用Generics。为您的Item对象定义一个接口并声明如下方法:

void CalcItems<T>(T item, int val) where T : IItem