[英]Initializer using a string for DataMember returning a static object of the class (factory pattern) in C#?
关于StackOverflow的第一个问题,我感到很害怕和兴奋。
我尝试使用静态对象作为工厂模式并仅使用类型作为字符串进行序列化的类具有确切的行为。 反序列化时,初始化器应基于字符串返回静态对象。
通过示例更容易做到:
[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也已经存在,我不一定要重新创建它。
我想要的是
var linear = new Interpolation
{
Type = "Linear"
};
回国
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.