如何在Print
内执行TestObject
?
class Program
{
private int Value;
static void Main()
{
TestObject test = new TestObject();
Program p1 = new Program();
Program p2 = new Program();
p1.Value = 1;
p2.Value = 2;
p1.Print();
p2.Print();
}
private void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
// How to execute p1.Print here?
}
答案 0 :(得分:1)
有多种方法可以做到这一点:
优点:
缺点:
Print
TestObject
与Program
联系起来以下是示例代码:
class Program
{
static void Main()
{
TestObject test = new TestObject(this);
}
public void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(Program p)
{
p.Print();
}
}
优点:
Print
TestObject
缺点:
TestObject
希望做某事,而不是TestObject
想要访问做某事的事情以下是示例代码:
class Program
{
static void Main()
{
TestObject test = new TestObject(() => Print());
}
private void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(Action print)
{
print();
}
}
优点:
缺点:
以下是示例代码:
interface IPrintable
{
void Print();
}
class Program : IPrintable
{
static void Main()
{
TestObject test = new TestObject(this);
}
public void Print()
{
Console.Write(Value.ToString());
Console.ReadKey();
}
}
class TestObject
{
public TestObject(IPrintable p)
{
p.Print();
}
}
结论:我的建议是选择界面方式。更清晰的设计,更容易扩展而无需传递多个代表。