最常见的可能是使用静态工厂方法:
public class object_t
{
public static object_t CreateObjectT(string config, object_t default_obj)
{
object_t theconfiguredobject = new object_t();
//try to configure it
if( /*failed to initialize from config*/ )
{
return default_obj.Clone();
}
else
{
return theconfiguredobject;
}
}
}
执行上述操作的更好方法是创建一个复制构造函数:
public object_t (object_t obj)
: this()
{
this.prop1 = obj.prop1;
this.prop2 = obj.prop2;
//...
}
以及尝试从配置字符串创建对象的方法:
private static bool TryCreateObjectT(string config, out object_t o)
{
//try to configure the object o
//if it succeeds, return true; else return false
}
然后让您的工厂方法首先调用 TryCreateObjectT,如果失败,则复制构造函数:
public static object_t CreateObjectT(string config, object_t default_obj)
{
object_t o;
return TryCreateObjectT(config, out o) ? o : new object_t(default_obj);
}