简体   繁体   English

即时将字符串转换为字符串数组

[英]Convert string to an array of strings on the fly

I have a method that returns an array of strings.我有一个返回字符串数组的方法。 In that method I am processing only one string, and I want to return it as an array of strings (an array of strings with only one element, which is my string → array[0] == myString ).在那个方法中,我只处理一个字符串,我想将它作为一个字符串数组返回(一个只有一个元素的字符串array[0] == myString ,即我的字符串 → array[0] == myString )。

I want that because I want to avoid some ugly code for creating an array of strings with one element, like that:我想要那个,因为我想避免使用一些丑陋的代码来创建一个包含一个元素的字符串数组,如下所示:

private static string[] FooterContent()
{
      string[] array = new string[1];
      array[0] = GetMyData();
      return array;        
}

I want something like that:我想要这样的东西:

private static string[] FooterContent()
{
      string myData = GetMyData();
      return myData.ToArray();        
}

And that myData.ToArray() should create an array with only one element ( array[0] = myString ) and then to return it.并且myData.ToArray()应该创建一个只有一个元素( array[0] = myString )的array[0] = myString ,然后返回它。

Or, something like that (if possible):或者,类似的东西(如果可能):

private static string[] FooterContent()
{
     return GetMyData().ToArray();        
}

The point is that I can't simply modify the return type from string[] to string because I am using the value returned from FooterContent (array of strings) and from other similar methods, like BodyContent or HeadContent , into another general method, WriteContent() that accepts an array of strings.关键是我不能简单地将返回类型从string[]修改为string因为我将从FooterContent (字符串数组)和其他类似方法(如BodyContentHeadContent )返回的值用于另一个通用方法WriteContent()接受字符串数组。

Is there an elegant way of doing this?有没有一种优雅的方式来做到这一点?

Thank you respectfully.恭敬地谢谢你。

As w0lf suggested in comments, the simplest way of creating an array would just be:正如 w0lf 在评论中建议的那样,创建数组的最简单方法就是:

return new[] { GetMyData() };

While you could create an extension method, I personally wouldn't - and if you do, you absolutely should not call it ToArray , as that already has a meaning for string due to Enumerable.ToArray and the fact that string implements IEnumerable<char> .虽然你可以创建一个扩展方法,我个人不会-如果你这样做,你绝对应该把它ToArray ,因为这已经有一个含义string由于Enumerable.ToArray和事实, string工具IEnumerable<char> .

If you really, really want to create this extension method, I'd do it as:如果你真的,真的想创建这个扩展方法,我会这样做:

public static T[] ToSingleElementArray(this T value)
{
    return new[] { value };
}

Then you can use:然后你可以使用:

return GetMyData().ToSingleElementArray();

But as I said, I wouldn't even create the extension method...但正如我所说,我什至不会创建扩展方法......

You can:你可以:

private static string[] FooterContent()
{
    return new[] { GetMyData() };        
}

or write extension method which isn't the best approach here (but possible):或编写扩展方法,这不是这里的最佳方法(但可能):

public static class StringExtensions
{
    public static string[] ToSingleElementArray(this string inputString)
    {
        return new[] { inputString };
    }
}

private static string[] FooterContent()
{
    return GetMyData().ToSingleElementArray();        
}

Try this,尝试这个,

private static string[] FooterContent()
{
     return new[] { GetMyData() };
}

Alternatively, you can wrap your GetData return value in a struct and use implicit operators to perform conversions:或者,您可以将GetData返回值包装在一个struct并使用隐式运算符来执行转换:

public struct DataResult
{
    private string _raw;
    private string[] _rawArray;

    public DataResult(string raw)
    {
        _raw = raw;
        _rawArray = new [] { raw };
    }

    private string Raw { get { return _raw; } }
    private string[] RawArray { get { return _rawArray; } }

    public static implicit operator string(DataResult result)
    {
        return result.Raw;  
    }

    public static implicit operator DataResult(string rawResult)
    {
        return new DataResult(rawResult);
    }

     public static implicit operator string[](DataResult result)
     {
         return result.RawArray;
     }

    public static implicit operator DataResult(string[] rawResultArray)
    {
        if(rawResultArray == null || rawResultArray.Length != 1)
            throw new ArgumentException("Raw result must be a single item array", "rawResultArray");

        return new DataResult(rawResultArray[0]);
    }
}

Implicit operators let you do implicit conversions from apples to pears (and viceversa):隐式运算符允许您进行从苹果到梨的隐式转换(反之亦然):

DataResult result = new DataResult("hello world");
string[] resultArray = result;
string rawResult = result;

DataResult result2 = new string[] { "hello world" };
DataResult result3 = "hello world";

What does it mean?这是什么意思? If your GetData method returns DataResult any other code can set its value to a string , string[] or DataResult , and perform the opposite conversions implicitly.如果您的GetData方法返回DataResult任何其他代码可以将其值设置为stringstring[]DataResult ,并隐式执行相反的转换。

I believe that in your case, this should be one of best approaches.我相信在你的情况下,这应该是最好的方法之一。

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

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