使用DataMember字符串的初始化程序在C#中返回类(工厂模式)的静态对象?

时间:2015-03-08 08:38:30

标签: c# static factory datacontract initializer

关于StackOverflow的第一个问题,我感到害怕和兴奋。

我尝试使用静态对象作为工厂模式,并使用类型作为字符串进行序列化,从而确实具有类的行为。反序列化时,Initializer应该根据字符串返回静态对象。

做一个例子比较容易:

[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
}

也许通过使用反射...... 谢谢:))

1 个答案:

答案 0 :(得分:1)

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);
        }
    }
}