首页 文章

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

提问于
浏览
1

关于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 回答

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

相关问题