是否可以做类似的事情:
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”方法,并避免使用不同的方法参数复制代码两次。我还想用一个对象作为参数,但我需要在那之后进行投射......你能建议我吗?
感谢。
答案 0 :(得分:2)
您的Customer1
和Customer2
应该从公共AbstractCustomer
类或ICustomer
接口继承。
这将允许您使用单方法来处理这两种方法,并且也不需要泛型:
static void DoSomething(ICustomer customer)
{
//... code here ...
InitializeCustomer(customer);
//... code here ...
}
static void InitializeCustomer(ICustomer c)
{
c.Reference = 1234;
c.Name = "John";
}
如@Reed Copsey所述,此解决方案假设两种类型都具有相同的成员。
如果为两者(方法签名的术语)提供相同的初始化方法,则可以单独初始化它们。
答案 1 :(得分:2)
由于Customer1
和Customer2
不共享公共接口,因此无法做到这一点。
但是,您可以重做这个,以便它们从基类(或接口)派生,并进行自己的初始化。这也会更加清晰,因为它允许每个Customer
初始化自己,从而使关注点更加清晰。
例如:
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) where T : Customer
{
//... code here ...
customer.Initialize();
//... code here ...
}
}
abstract class Customer
{
public abstract void Initialize();
}
class Customer1 : Customer
{
public int Reference;
public string Name;
public override void Initialize()
{
this.Reference = 1234;
this.Name = "John";
}
}
class Customer2 : Customer
{
public string Name;
public string Town;
public override void Initialize()
{
this.Name = "Mary";
this.Town = "Tokyo";
}
}
答案 2 :(得分:0)
您需要有一个单独的类实例来执行此操作。
更好的方法是使用继承,一旦客户从另一个继承,或者更好的是,两者都从公共基础继承。然后,您可以通过调用适当的方法在任何地方放置初始化例程,并调用正确的版本。
答案 3 :(得分:0)
也许共享界面?
interface ICustomer
{
void Initialize();
}
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) where T : ICustomer
{
customer.Initialize();
}
}
class Customer1 : ICustomer
{
public void Initialize()
{
Reference = 1234;
Name = "John";
}
public int Reference;
public string Name;
}
class Customer2 : ICustomer
{
public void Initialize()
{
Name = "Mary";
Town = "Tokyo";
}
public string Name;
public string Town;
}