简体   繁体   English

工厂模式C中缺少返回语句

[英]missing return statement in factory pattern c#

I have the following code for my code but it always says the return statement is missing, even though I have put them in a switch list. 我的代码有以下代码,但是即使我将它们放在切换列表中,它也总是说return语句丢失了。

public IMap Map(string oldtheme) 
{ 
    switch (oldtheme) 
    { 
        case "archer": return new Archer(); 
        case "craftyblue": return new CraftyBlue(); 
        case "minimal": return new Minimal(); 
        case "mintalicious": return new Mintalicious(); 
        case "misfit": return new Misfit(); 
        case "peach": return new Peach(); 
        case "queen": return new Queen(); 
        case "sketch": return new Sketch(); 
        case "takeaway": return new TakeAwayLemonFresh(); 
        case "lemonfresh": return new TakeAwayLemonFresh(); 
        case "vanilla": return new Vanilla(); 
        case "velvet": return new Velvet(); 
        case "victoriana": return new Victoriana(); 
        case "writer": return new Writer();
    }
}

You need to handle the case when oldtheme is none of the values you check for. oldtheme不是您要检查的值时,您需要处理这种情况。

Depending on your case, I suggest throwing a ArgumentException so you know when it happens. 根据您的情况,我建议抛出ArgumentException以便您知道它何时发生。 I have added a default case to your switch statement: 我在您的switch语句中添加了default情况:

public IMap Map(string oldtheme)
{
    switch ( oldtheme )
    {
        case "archer": return new Archer();
        case "craftyblue": return new CraftyBlue();
        case "minimal": return new Minimal();
        case "mintalicious": return new Mintalicious();
        case "misfit": return new Misfit();
        case "peach": return new Peach();
        case "queen": return new Queen();
        case "sketch": return new Sketch();
        case "takeaway": return new TakeAwayLemonFresh();
        case "lemonfresh": return new TakeAwayLemonFresh();
        case "vanilla": return new Vanilla();
        case "velvet": return new Velvet();
        case "victoriana": return new Victoriana();
        case "writer": return new Writer();
        default: throw new ArgumentException("unexpected value of oldtheme");
    }
}

You lack a default value. 您缺少默认值。 Just add; 只需添加;

default: return null;

At the bottom of your switch and you'll be fine. switch的底部,您会没事的。

What do you want to return if the string is none of those you have in your switch? 如果该字符串不是您的交换机中的所有字符串,您想返回什么? Your function is missing a return statement for that case. 您的函数缺少该情况的return语句。

您必须在每个return命令之后使用break,它将可以正常工作。

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

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