簡體   English   中英

初始化程序使用DataMember的字符串返回C#中類(工廠模式)的靜態對象嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM