使用字符串作为DataMember的初始值设定项,返回C#中类(工厂模式)的静态对象?
关于StackOverflow的第一个问题,我感到害怕和兴奋 我试图为一个使用静态对象作为工厂模式并仅使用类型作为字符串进行序列化的类提供精确的行为。反序列化时,初始值设定项应基于字符串返回静态对象 通过一个例子更容易做到:使用字符串作为DataMember的初始值设定项,返回C#中类(工厂模式)的静态对象?,c#,static,factory,datacontract,initializer,C#,Static,Factory,Datacontract,Initializer,关于StackOverflow的第一个问题,我感到害怕和兴奋 我试图为一个使用静态对象作为工厂模式并仅使用类型作为字符串进行序列化的类提供精确的行为。反序列化时,初始值设定项应基于字符串返回静态对象 通过一个例子更容易做到: [DataContract] public class Interpolation { [DataMember] public string Type { get; set; } public static Interpolation Linear
[DataContract]
public class Interpolation
{
[DataMember]
public string Type { get; set; }
public static Interpolation Linear = new Interpolation(...)
}
我想用不同的方法得到一个线性插值:
var interpolation = Interpolation.Linear;
var linear = new Interpolation
{
Type = "Linear"
};
第一个是工厂模式(某种类型),第二个用于反序列化
我尝试了一些解决方案。通常我有一个通用构造函数,我使用特定的参数来创建静态对象。它将成为:
[DataContract]
public class Interpolation
{
[DataMember]
public string Type
{
get { return _type; }
set
{
_type = value;
_interpolation = Select(value);
}
}
private string _type = "Linear"; // Default
private Func<double, double[], double[], double> _interpolation;
private Interpolation(Func<double, double[], double[], double> interpolation, string type)
{
_interpolation = interpolation;
_type = type;
}
public static Interpolation Linear = new Interpolation(_linear, "Linear");
private double _linear(double x, double[] xx, double[] yy)
{
...
}
返回
Interpolation.Linear
构造函数无法返回类的静态对象:
public Interpolation(string type)
{
return Interpolation.Linear; // Won't work
}
也许通过使用反射。。。
谢谢:)
new
用于创建新实例。如果您试图使用它返回一个现有实例,那么您是做错了。就跟单身汉呆在一起吧
var interpolation = Interpolation.Linear;
或者使用这样的工厂
public static class InterpolationFactory
{
public static Interpolation GetInterpolation(string type, Func<double, double[], double[], double> interpolation = null)
{
if (type == "Linear")
{
return Interpolation.Linear;
}
else
{
return new Interpolation(interpolation);
}
}
}
公共静态类插值工厂
{
公共静态插值GetInterpolation(字符串类型,Func Interpolation=null)
{
如果(类型=“线性”)
{
返回插值。线性;
}
其他的
{
返回新插值(插值);
}
}
}
我认为它不适合反序列化。当客户机收到Type=“Linear”的DataContract时,我相信它将调用一个无参数构造函数。所以我的问题是,当反序列化如何返回类的静态对象时,关于InterpolationFactory类,我试图避免为相同类型的对象创建第二个类。但我完全同意,您可以在DataContract中使用Type的值来调用工厂类,该类将返回预期的对象。@isidore12,是的,您应该试试。如果你不成功,我稍后再试试。@ ISIDORY12-至于序列化/反序列化,你可能要考虑解耦——即仅仅序列化“类型”字符串或一些插值参数对象,如果它更紧凑;然后使用工厂方法从类型(或插值参数)构造插值实例。请注意,反序列化不会调用任何构造函数。对象将直接在内存中创建。如果反序列化后需要一些自定义操作,只需创建一个方法并用OnDeserializedAttribute
标记它。
public static class InterpolationFactory
{
public static Interpolation GetInterpolation(string type, Func<double, double[], double[], double> interpolation = null)
{
if (type == "Linear")
{
return Interpolation.Linear;
}
else
{
return new Interpolation(interpolation);
}
}
}