繁体   English   中英

非静态类工厂方法-C#

[英]non-static class factory method - C#

我将其组合起来以解析出一个字符串,然后在一个SQL存储过程中返回3个值(我还有另一个C#方法,它根据您选择的输出格式来格式化3个值,但是该代码没有问题,所以我没有发表它)。 当我的老板看到我的代码时,他说:

“您如何有一个非静态的类工厂方法?您需要创建一个对象来解析字符串以创建要使用的对象吗?

为什么将分析移到该类中,而不是将其保留在原来的位置,而只是将其传递回新类以保存数据?”

我上了一堂新课,但是我可以轻松地将其转移到另一堂课。 问题是我不知道他的非静态工厂方法什么意思,而且我也不知道如何在不像我那样创建TwpRng的新实例的情况下赋值,小数和方向 :TwpRng result = new TwpRng( );

这是我在C#BTW的第一个裂缝。

public class TwpRng
{
public string Value;
public string Fraction;
public string Direction;


public TwpRng GetValues(string input)
{
    TwpRng result = new TwpRng();
    result.Value = "";
    result.Fraction = "";
    result.Direction = "";

    Regex pattern_1 = new Regex(@"(?i)^\s*(?<val>\d{1,3})(?<frac>[01235AU])(?<dir>[NEWS])\s*$");    // Example:  0255N
    Match match_1 = pattern_1.Match(input);

    Regex pattern_2 = new Regex(@"(?i)^\s*(?<val>\d{1,3})(?<dir>[NEWS])\s*$");    // Example:  25N
    Match match_2 = pattern_1.Match(input);

    Regex pattern_3 = new Regex(@"(?i)^\s*(?<val>\d{1,3})(?<frac>[01235AU])\s*$");    // Example:  25A
    Match match_3 = pattern_1.Match(input);

    if (match_1.Success)
    {
        result.Value = match_1.Groups["val"].Value;
        result.Fraction = match_1.Groups["frac"].Value;
        result.Direction = match_1.Groups["dir"].Value.ToUpper();             
    }
    else if (match_2.Success)
    {
        result.Value = match_2.Groups["val"].Value;
        result.Direction = match_2.Groups["dir"].Value.ToUpper();
    }
    else if (match_3.Success)
    {
        result.Value = match_3.Groups["val"].Value;
        result.Fraction = match_1.Groups["frac"].Value;
    }
    else
    {
        result = null;
    }
    return result;
}

}

您如何有一个非静态的类工厂方法? 您需要创建一个对象来分析字符串以创建要使用的对象吗?

他的意思是,当前要解析输入,您需要执行以下操作:

var twpRng = new TwpRng(); // Doesn't really make sense to instantiate an empty object
twpRng = twpRng.GetValues(input); // just to create another one.

如果将工厂方法GetValues 静态

public static TwpRng GetValues(string input)

您可以更轻松地解析:

var twpRng = TwpRng.GetValues(input);

如果您更改:

public TwpRng GetValues(string input)

至:

public static TwpRng GetValues(string input)

您已从非静态工厂模式更改为静态工厂模式。 两者的调用顺序如下:

TwpRng myRng = new TwpRng();
TwpRng createdRng = myRng.GetValues(input);

相对于:

TwpRng createdRng = TwpRng.GetValues(input);

您的其余代码可以相同。

扩展说明

老板问的是static修饰符的使用。 可以在不首先实例化该类(创建其实例)的情况下调用静态方法,并且这些静态方法通常用于解析数据并返回该类的完全水合实例。 静态方法也可以用于实用程序类和方法(其中实例化的对象可能会导致过度杀伤),而您只想对一堆功能进行分组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM