简体   繁体   English

C#中的条件Streamwrite

[英]Conditional Streamwrite in C#

Say I have a list of member, each of which is a custom object: 说我有一个成员列表,每个成员都是一个自定义对象:

public class pail
{
    public string milk;
    public string water;
    public string butter;
    public string beer;
}



public class AddToPail()
{
    private List<pail> _pailList = new List<pail>();
    PSVM(String[] args)
    {
        for(int i = 0; i < 200; i++)
        {
            pail newPail = new Pail();
            switch(i)
            {
                case 1:
                {
                    newPail.milk = "This pail has milk";
                }
                break;
                case 2:
                {
                    newPail.butter = "This pail has butter";
                }
                break;
                case 3:
                {
                    newPail.water = "This pail has water";
                }
                break;
                case 4:
                {
                    newPail.beer = "This pail has beer";
                }
                break;
            }
            _pailList.Add(newPail);
        }
        foreach (pail thisPail in _pailList)
        {
            using (StreamWriter SW = new StreamWriter(@"C:\pail.txt")
            {
                if (!thisPail.milk.IsNullOrEmpty())
                {
                    SW.WriteLine(thisPail.milk);
                }
                else if (!thisPail.butter.IsNullOrEmpty())
                {
                    SW.WriteLine(thisPail.butter);
                }
                else if (!thisPail.beer.IsNullOrEmpty())
                {
                    SW.WriteLine(thisPail.beer);
                }
                else if (!thisPail.water.IsNullOrEmpty())
                {
                    SW.WriteLine(thisPail.water);
                }
                else
                {
                    Console.Writeline("oops");
                }
            }
        }
    }
}

Say I want to set up a StreamWriter that only prints the true values without having to write a million if, else if, else statements... is there an easy way or library to do this in C#? 说我想设置一个StreamWriter,它只打印真实值,而如果不是,则写一百万,否则,否则...在C#中是否有简单的方法或库可以做到这一点? I'm basically looking for a way to only print out true values in a neat, concise way. 我基本上是在寻找一种仅以简洁明了的方式打印出真实值的方法。 Does anyone have any advice as to how I should approach this? 有人对我应该如何处理有任何建议吗?

Thank you very much! 非常感谢你!

EDIT So the ultimate goal of this is that I have an object that has around 20 members. 编辑所以,这的最终目标是我有一个大约有20个成员的对象。 The object is automatically populated, and the populating script can leave some of the members empty. 该对象将自动填充,并且填充脚本可以将某些成员保留为空。 I'd like to be able to print the members in a CSV format, and not have to have 20 if statements to see if a particular member in the object has been instantiated before outputting via the streamwriter. 我希望能够以CSV格式打印成员,而不必通过20条if语句来查看对象中的特定成员是否已通过流写入器输出之前被实例化。

Edit 2 编辑2

I changed my code to be a little closer to what I needed it to do. 我将代码更改为与我需要执行的代码更加接近。 Sorry for the previous poor explanation. 抱歉,以前的解释不好。

I think you should refactor your program a little bit. 我认为您应该对程序进行一些重构。 For starters, I would use an enum for bucket contents: 首先,我将为存储桶内容使用一个枚举:

public enum EBucketContents { Milk, Water, Butter, Beer };

Then, instead of having a list of booleans, you can use a dictionary: 然后,可以使用字典来代替布尔值列表:

var pail = Dictionary<EBucketContents,bool>();

Now it's a simple matter to only output the ones that are true: 现在只需要输出正确的值就很简单了:

foreach( var kvp in pail.Where( x => x.Value ) ) {
    SW.WriteLine( "pail has " + kvp.Key.ToString().ToLower() )
}

If you just want to save some typing, use this extension method: 如果只想保存一些键入内容,请使用以下扩展方法:

internal static class Extensions
{
    public static void WriteLineIf(this TextWriter tw, bool condition, string text)
    {
        if (condition)
        {
            tw.WriteLine(text);
        }
    }
}

But it looks like only one of those bools can be true, since you're using else if blocks. 但是看起来这些布尔值中只有一个是正确的,因为您正在使用else if块。

In that case, use and enum 在这种情况下,使用和枚举

internal enum Pail
{
    Butter,
    Milk,
    Water,
    Beer
}

Can you just use a Dictionary where the key is the field name and the value is the fields value. 您可以只使用一个字典,其中键是字段名称,值是字段值。 This way you don't need to check if the output is filled or not - you just output all fields 这样,您无需检查输出是否已填充-您只需输出所有字段

Your populating script can populate the dictionary keys only if they are set 您的填充脚本只有在设置了字典键后才能填充

Then your streamwriter can just go 那你的流媒体作家就可以去了

foreach(KeyValuePair<string, string> kvp in fieldsDict)
   sw.Write("Key: " + kvp.Key + ", Value: " + kvp.Value);

Or even just a list of string/or enum 甚至只是一个字符串列表或枚举

eg 例如

public class pail
{
    public List<string> Fields = new List<string>();
}


public class AddToPail()
{
    private List<pail> _pailList = new List<pail>();

    PSVM(String[] args)
    {
        for(int i = 0; i < 200; i++)
        {
            pail newPail = new Pail();
            switch(i)
            {
                case 1:
                {
                   newPail.Fields.Add("This pail has milk");
            }
            break;
         *** SNIP

Of course using a Dictionary could solve your problem , but I'm not really fond of this kind of solution, since it makes you lose some control over what you are putting in, eg you could end up with a pail having airplanes... I'd refactor your code in something like this, trying to give every class its own responsabilities (BTW I don't like AddToPail as a class name, it's more a method name): 当然,使用字典可以解决您的问题,但是我不太喜欢这种解决方案,因为它会使您对所放内容失去控制,例如,最终可能会得到装有飞机的提桶...我将以这种方式重构您的代码,尝试赋予每个类自己的职责(顺便说一句,我不喜欢AddToPail作为类名,它更是一个方法名):

public class Pail
{
    public string milk;
    public string water;
    public string butter;
    public string beer;

   private bool everythingEmpty = true;

    public Pail(int i)
    {
            switch(i)
            {
                case 1:
                {
                    milk = "This pail has milk";
                    everythingEmpty = false;
                }
                break;
                case 2:
                {
                    butter = "This pail has butter";
                    everythingEmpty = false;
                }
                break;
                case 3:
                {
                    water = "This pail has water";
                    everythingEmpty = false;
                }
                break;
                case 4:
                {
                    beer = "This pail has beer";
                    everythingEmpty = false;
                }
                break;
            }
    }

    public void WriteToStream(StreamWriter SW)
    {
           if (everythingEmpty)
           {
               Console.Writeline("oops");
               return;
           }
           WriteToStream(milk, SW);
           WriteToStream(butter, SW);
           WriteToStream(beer, SW);
           WriteToStream(water, SW);
    }

    public static void WriteToStream(string content, StreamWriter SW)
    {
                if (!content.IsNullOrEmpty())
                {
                    SW.WriteLine(content);
                }
    }
}



public class AddToPail()
{
    private List<pail> _pailList = new List<pail>();
    PSVM(String[] args)
    {
        for(int i = 0; i < 200; i++)
        {
            pail newPail = new Pail(i);
            _pailList.Add(newPail);
        }
        foreach (pail thisPail in _pailList)
        {
            using (StreamWriter SW = new StreamWriter(@"C:\pail.txt")
            {
                thisPail.WriteToStream(SW);
            }
        }
    }
}

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

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