是否有可能做這樣的事情:方法參數和過載
class Program
{
static void Main(string[] args)
{
Customer1 c1 = new Customer1();
DoSomething(c1);
Customer2 c2 = new Customer2();
DoSomething(c2);
}
static void DoSomething<T>(T customer)
{
//... code here ...
InitializeCustomer(customer); // <- error indeed :-(
//... code here ...
}
static void InitializeCustomer(Customer1 c1)
{
c1.Reference = 1234;
c1.Name = "John";
}
static void InitializeCustomer(Customer2 c2)
{
c2.Name = "Mary";
c2.Town = "Tokyo";
}
}
class Customer1
{
public int Reference;
public string Name;
}
class Customer2
{
public string Name;
public string Town;
}
我想,以避免造成2「DoSomething的」方法,也避免了用不同的方法參數兩次複製代碼。我想用一個對象作爲參數,但我需要在之後施放......你能指導我嗎?
謝謝。
+1。我不知道這在C#中是不允許的(它在C++中有效) – finnw 2011-02-03 19:11:20