-1

我正在尝试尽可能地缩短和改进我的代码。我的想法之一是从一行代码返回一个字符串,using用于确保在事务完成后访问的文件再次可用。我的目标是尽可能接近单行代码,但是我很难找到解决字符串不变性的方法。

以下代码无效:

string sample()
{
    try{ using( string example = (new StreamReader
                                 (new FileStream
                                 ("", FileMode.Open, FileAccess.Read),
                                 Encoding.UTF8).ReadToEnd())) }
    //I haven't quite worked out returning the value yet, but this is irrelevant here
}

工作代码如下:

string sample()
{
    FileStream fs = new FileStream("", FileMode.Open, FileAccess.Read);
    try{
        using(StreamReader rdr = new StreamReader(fs);
        return rdr.ReadToEnd();
       }
}

我可以通过执行以下操作轻松简化这一点:

string sample()
    {
        try
        {
            return (new StreamReader(new FileStream
                                    ("", FileMode.Open, FileAccess.Read),
                                    Encoding.UTF8).ReadToEnd());
        }
    }

但是,交易完成后可能不会关闭文件(如果有误,请告诉我)。有没有办法解决这里字符串的不变性,还是我在寻找不可能的事情?

4

1 回答 1

1

看起来您想要一种从using语句创建表达式的方法。您可以创建一个函数:

public static T Use<TRec, T>(TRec resource, Func<TRec, T> f) where TRec : IDisposable
{
    using(resource) { return f(resource); }
}

然后做

string s = Use(new StreamReader(new FileStream("", FileMode.Open, FileAccess.Read), Encoding.UTF8), sr => sr.ReadToEnd());
于 2017-07-12T13:05:46.033 回答