[英]C# Switch type for multiple Dictionary types
I want to add Switch case based on type of input parameter.我想根据输入参数的类型添加 Switch case。 Eg My input parameter can be of type double, Dictionary<int, string>, Dictionary<decimal, bool>
例如,我的输入参数可以是 double 类型,Dictionary<int, string>, Dictionary<decimal, bool>
For that I have added below switch case which calls correctly for both Dictionary types mentioned above but from there i have to call another function which will log that Dictionary.为此,我在下面添加了开关盒,它可以正确调用上述两种字典类型,但从那里我必须调用另一个函数来记录该字典。 For that function i have taken input as Dictionary<object, object> so that it can accept both types of dictionary but it is unable to cast above dictionary types to Dictionary<object, object>
对于该函数,我将输入作为 Dictionary<object, object> 以便它可以接受两种类型的字典,但无法将上述字典类型转换为 Dictionary<object, object>
Below is my complete code下面是我的完整代码
static void Main(string[] args) {
Dictionary < int, string > dict = new Dictionary < int, string > () {
{
1,
"One"
}, {
2,
"Two"
}
};
Dictionary < decimal, bool > dict2 = new Dictionary < decimal, bool > () {
{
1,
true
}, {
2,
false
}
};
Double doubleObj = 100.2;
HandleLogging(doubleObj);
HandleLogging(dict);
HandleLogging(dict2);
}
private static void HandleLogging(Object obj) {
switch (obj) {
case double _:
Console.WriteLine($"Dobule data type ..");
break;
case Dictionary < int, string > _:
case Dictionary < decimal, bool > _:
// case object dictType2 when dictType2 == typeof(Dictionary<decimal, bool>):
//case Dictionary<object, object> d:
Console.WriteLine($"Dictionary data type..");
HandleDictionary((Dictionary < object, object > ) obj);
break;
default:
Console.WriteLine("unknown type");
break;
}
}
private static void HandleDictionary(Dictionary < object, object > existingDictionary) {
Console.WriteLine(string.Format("Dictionary object : {0}", JsonConvert.SerializeObject(existingDictionary)));
}
From pure "how do I do it" point of view (without discussing why and is it a good practice in general case) - Dictionary<TKey, TValue>
implements IDictionary
(which is non-generic version of dictionary) so you can match against it:从纯粹的“我该怎么做”的角度来看(不讨论为什么以及在一般情况下这是一个好习惯) -
Dictionary<TKey, TValue>
实现IDictionary
(这是字典的非通用版本),因此您可以匹配它:
case IDictionary _:
Console.WriteLine($"Dictionary data type..");
Console.WriteLine("Dictionary object : {0}", JsonConvert.SerializeObject(obj));
break;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.