2016-02-27 83 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