【问题标题】:checking for values in multiple if statement and storing multiple comments based on results检查多个 if 语句中的值并根据结果存储多个注释
【发布时间】:2014-05-08 16:06:59
【问题描述】:

谁能给我一个从 if 语句返回多个 cmets 的最佳方法的示例?

  protected string CheckFacility(int FacilityId)
{
    var cfacility = new List<string>();
    BuildingPresenter b = new BuildingPresenter();
    FunctionalAreaPresenter f = new FunctionalAreaPresenter();
    if (b.GetBuildings(FacilityId) != null)
    {
        cfacility.Add("There are Functional Areas associated with this facility. ");
    }


    if (f.GetFunctionalAreas(FacilityId) != null) 
    {
        cfacility.Add("There are Functional Areas associated with this facility. ");
    }

    var cfacilitystring = string.Join(",", cfacility);

我收到这些错误。

错误 3 'string.Join(string, string[])' 的最佳重载方法匹配有一些无效参数

错误 4 参数 2:无法从 'System.Collections.Generic.List' 转换为 'string[]'

【问题讨论】:

  • 嗯?您有一个 3 条件 if 语句,这与返回有什么关系?你到底想完成什么?
  • 是的,您可以通过各种不同的方式返回多个值。在我们回答问题之前,您需要让我们更清楚地了解您正在尝试做什么以及您尝试过什么。
  • 一个方法只能有一个返回值。在上述情况下,听起来您正在尝试存储选定的选项 - 所以除非衬衫是黑色的、大的并且有长袖(这将是一个奇怪的条件),否则我会创建一个对象存储所有选定的选项并返回该对象。
  • 也许您应该提供您编写的代码,或者尝试编写一些代码并显示它没有按照您的意愿执行的操作。它不必编译,只需准确传达您想要完成的任务,以便我们知道如何为您提供帮助。
  • 假设颜色、尺码或衬衫类型并不重要。我想根据存在的属性向用户发送消息。因此消息可以返回任何组合,例如颜色和尺寸,或者可能只是衬衫类型。我只是想找出最好的方法来做到这一点。我正在尝试检查这些属性是否存在。

标签: c# asp.net


【解决方案1】:
var shirtAttributes = new List<string>();
if (shirt.IsBlack)
{
    shirtAttributes.Add("black");
}
if (shirt.IsLarge)
{
    shirtAttributes.Add("large");
}
if (shirt.IsLongSleeve)
{
    shirtAttributes.Add("long sleeve");
}
var shirtAttributesString = string.Join(",", shirtAttributes);

输出类似于:“黑色,长袖”或“黑色”或“大号,长袖”

【讨论】:

  • 我遇到了这些错误。你能帮忙吗?谢谢!错误 3 'string.Join(string, string[])' 的最佳重载方法匹配有一些无效参数错误 4 参数 2:无法从 'System.Collections.Generic.List' 转换为 'string[]
【解决方案2】:

你有很多方法可以解决这个问题,你可以创建一个类并覆盖 ToString() 方法:

  public class Shirt{

    public Shirt(string color, string size, string sleeve)
    {
     Color =color;
     Size=size;
     Sleeve=sleeve;
     }
    public string Color {get;set;}
    public string Size {get;set}
    public string Sleeve {get;set}


    public override string ToString(){

     return string.Format("shirt is color :{0} , size :{1} and shleeve: {2}",Color,Size,Sleeve )

    }

  }

所以当你在用值初始化你的类之后运行你的程序时

Shirt myShirt = new Shirt("black","large","long");
if(myShirt.Color=="black"&& myShirt.Size=="large" && myShirt.Sleeve=="long")
{
 return myShirt.ToString(); 
 }
else{
 return "no match";//or want you want
 }

希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多