J. *_*uez -1 c# iif-function iif
In Visual Basic, there is this IIF Function, as in Crystal Report, etc ...
In C # itself, this function does not exist, but it is the same as doing something like this:
bool a = true;
string b = a ? "is_True" : "is_False";
Run Code Online (Sandbox Code Playgroud)
But for the code to be a bit easier to read I wanted to do it as a function for C #, leaving it like this:
public static T IIf<T>(bool expression, T truePart, T falsePart)
{
return expression ? truePart : falsePart;
}
Run Code Online (Sandbox Code Playgroud)
Or to not operate with the real values ??can also be done using delegates, to access the necessary values:
public static T IIf<T>(bool expression, Func<T> truePart, Func<T> falsePart)
{
return expression ? truePart() : falsePart();
}
Run Code Online (Sandbox Code Playgroud)
So far this works well ...
But how can I modify this function so I can take 2N + 1 arguments?
(N - the number of logical expressions specified)
Example the desired result:
Each odd argument specifies a logical expression;
Each even argument specifies the value that is returned if the previous expression evaluates to true;
The last argument specifies the value that is returned if the previously evaluated logical expressions yielded false.
int value = IIf(Name = "Joel", 1, Name = "Peter", 2, Name = "Maria", 3, 4);
Run Code Online (Sandbox Code Playgroud)
Can someone give me a hand with this?
Environment: C # - Visual Studio 2017
首先,如评论中所述,这是一个坏主意。较新版本的C#已经支持模式匹配开关作为该语言的内置功能。用它。
其次,这是一个坏主意,因为API“ argument,case1,result1,case2,result2,...”的签名很难在C#类型系统中表达。
如果我被迫实现这样的API,我建议使用元组:
public static R Switch<A, R>(
A item,
R theDefault,
params (A, R)[] cases )
{
foreach(var c in cases)
if (item.Equals(c.Item1))
return c.Item2;
return theDefault;
}
Run Code Online (Sandbox Code Playgroud)
或者,制作有用的实用程序方法并使用它:
public static T FirstOrDefault(
this IEnumerable<T> items,
T theDefault,
Func<T, bool> predicate)
{
foreach(var i in items.Where(predicate))
return i;
return theDefault;
}
public static R Switch<A, R>(
A item,
R theDefault,
params (A, R)[] cases ) =>
cases.FirstOrDefault(
(item, theDefault),
c => item.Equals(c.Item1)).Item2;
Run Code Online (Sandbox Code Playgroud)
如果由于使用的是较旧版本的C#而无法使用元组,则可以创建自己的对类型或使用键值对类型。
但是只是不要去那里。如果需要开关,请编写开关。如果您需要字典,请编写字典。
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |