0

所以,标题有点误导,我先整理一下。

考虑以下代码:

public static ADescription CreateDescription(string file, string name, params string[] othername)
{
    return new ADescription(file, name, othername.ToList<string>());
}

这将System.ArgumentNullException在用户最后故意输入 null 的情况下抛出。例如:

ADescription.CreateDescription("file", "name", null); // example

现在我有一个基本上获取和设置othername列表的属性。我担心的是,我必须在每个阶段进行检查,例如(在属性中以及在此方法中):

if (othername == null){
   // do nothing
}
else{
    othername.ToList<string>; // for example
}

因为, null 是可以接受的othername。有没有什么方法可以让 c# 原生地提供这种功能,如果othername为空,那么它就不会真正操作 ToList() 。

4

2 回答 2

1

您可以使用三元运算符:

 return new ADescription(file, name, othername==null?null:othername.ToList<string>());

或者按照此处接受的响应中所述创建扩展方法使用此(基于扩展方法的)速记的可能陷阱

public static class IfNotNullExtensionMethod
{
    public static U IfNotNull<T, U>(this T t, Func<T, U> fn)
    {
        return t != null ? fn(t) : default(U);
    }
}

您的代码将是:

return new ADescription(file, name, othername.IfNotNull(on => on.ToList());
于 2013-07-05T03:36:08.290 回答
0

You could make an extension method to handle this:

public static class MyExtensionMethods
{
    public static List<T> ToListIfNotNull<T>(this IEnumerable<T> enumerable)
    {
        return (enumerable != null ? new List<T>(enumerable) : null);
    }
}

Then you can substitute the extension method wherever you would otherwise use ToList().

return new ADescription(file, name, othername.ToListIfNotNull());
于 2013-07-05T03:51:10.917 回答