我有一个使用Y类的X类.X创建Y,但X必须创建Y,使用相同的构造函数方法创建传递给X的实例Y.
我想将类Y的“构造函数方法和参数”传递给类X,并使用此信息,使用ctor-method-passed创建新的Y实例。
而且我不想发展所有'Class Y'构造函数逻辑,因为在这种情况下,它们都会非常高度耦合。
我做了一点点飙升来解释自己好一点。
感谢。
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TheSon son1 = new TheSon();
son1.TheValue = "Another Value";
TheFather<TheSon> father1 = new TheFather<TheSon>(son1);
Console.WriteLine("Result is {0}:", "Empty constructor".Equals(father1.MySon.TheValue));
Console.WriteLine("\tbecause prop. must be: '{0}' and it is: '{1}'", "Empty constructor", father1.MySon.TheValue);
}
public class TheFather<T> where T: TheSon
{
public TheSon MySon { get; set; }
public TheFather(T mySon) {
// I would like to NOT use the same object but
// use the constructor that was used to build the passed object-instance.
//
// Or perhaps pass a concrete TheSon constructor to the 'TheFather'...
this.MySon = (TheSon)mySon;
}
}
public class TheSon
{
public string TheValue { get; set; }
public TheSon()
{
this.TheValue = "Empty constructor";
}
public TheSon(string value)
{
this.TheValue = value;
}
public TheSon(string value, int element)
{
this.TheValue = value + "-> " + Convert.ToString(element);
}
}
}
}
======的解: 将此构造函数添加到TheFather类:
public TheFather(Func<T> sonFactory)
{
this.MySon = (T)sonFactory();
}
这个例子:
static void Main(string[] args)
{
// Uncomment one of this to change behaviour....
//Func<TheSon> factory = () => new TheSon();
Func<TheSon> factory = () => new TheSon("AValue");
//Func<TheSon> factory = () => new TheSon("AValue", 1);
TheFather<TheSon> father1 = new TheFather<TheSon>(factory);
Console.WriteLine("Result is {0}:", "AValue".Equals(father1.MySon.TheValue));
Console.WriteLine("\tbecause prop. must be: '{0}' and it is: '{1}'", "AValue", father1.MySon.TheValue);
}
像魅力一样....: - )
...谢谢
答案 0 :(得分:0)
您只需使用工厂创建TheSon
个对象:
Func<TheSon> factory = () => new TheSon(); // creates one with default ctor
这样你每次都可以得到一个新对象,但是以完全相同的方式创建(这不仅限于构造函数;你还可以包含你想要的任何其他代码)。像这样使用它:
var oneSon = factory(); // creates one son
var secondSon = factory(); // creates another with the same constructor
var father = new TheFather(factory()); // ditto
更新:如果要在TheFather
内创建TheSon
,也可以更改TheFather
的构造函数以接受工厂。例如:
public TheFather(Func<T> sonFactory) {
this.MySon = (TheSon)sonFactory();
}
和
var father = new TheFather(factory);