switch 语句:“需要一个常量值"; [英] switch statement: "a constant value is expected"
问题描述
目前我正在与神奇的字符串"问题作斗争:
Currently I'm fighting with that "magical strings" issue:
public class MyDataField
{
// class definition
}
// exuecuted method
public void SwitchMultipleDataFields()
{
var myField = new MyDataField();
switch(myField.GetType().ToString())
{
// only case, which works
case "MyDataField":
// case operations
break;
// other option:
case typeof(MyDataField).ToString():
// case operations
break;
// other cases of other FieldTypes
}
}
现在我收到了我写在我的线程标题中的错误消息.我认为问题在于这个字符串在非编译时"时不是常量.因此,要求切换的唯一可能方法是通过明确确定该 case 字符串的值.我的问题只是我没有收到编译错误,以防我重命名 MyDataField
类.所以这些类中的 90% 无论如何都是通用的.这些在 switch 语句的 default
中处理.除了明确确定 case 值的值之外,还有其他方法吗?
Now I get the error Message I've written in the title of my thread. I think the problem is that this string is not a constant while "non-compile-time". So the only possible way to ask switch this is via explicitly determining the value of that case string. My problem just is that I don't get an compile error in case I'd rename the MyDataField
class. So 90% of these classes are generic anyway. These are handled in the default
of the switch statement. Isn't there another way than explicitly determining the value of the case value?
请不要争论这种方法的意义.我写这个是为了用更简单的方式说明我的问题
Please don't argue about the sense of this method. I've just written that to illustrate my problem in an easier way
推荐答案
使用新的 C# 7 的模式匹配特性 我会用下面的方式解决它.
With the new pattern matching feature of C# 7 I would solve it in the following manner.
这里是一个简单的 Field
和 Document
类
Here a simple Field
and Document
class
public class Field
{
public string Label { get; set; }
}
public class Field<T> : Field
{
public T Value { get; set; }
}
public class Document
{
public string Content { get; set; }
}
这里是一个 FieldOperator
类,它对 Field
s 的列表进行一些任意更改
And here a FieldOperator
class which does some arbitrary changes to a list of Field
s
public static class FieldOperator
{
public static void Operate(Field[] fields)
{
foreach (var field in fields)
{
field.Label = field.GetType().ToString();
switch (field)
{
case Field<Document> docField:
docField.Value.Content = "Foo Bar";
break;
case Field<int> intField:
intField.Value = 600842;
break;
default:
field.Label = "Oops";
break;
}
}
}
}
测试这些操作"的正确性
Testing for correctness of these "operations"
[Test]
public void OperationsAreCorrect()
{
var docField = new Field<Document> {Value = new Document {Content = "Hello World"}};
var intField = new Field<int> {Value = 17};
var dateField = new Field<DateTime>();
FieldOperator.Operate(new Field[] {docField, intField, dateField});
Assert.IsTrue(docField.Label == docField.GetType().ToString());
Assert.IsTrue(intField.Label == intField.GetType().ToString());
Assert.IsTrue(dateField.Label == "Oops");
Assert.IsTrue(docField.Value.Content == "Foo Bar");
Assert.IsTrue(intField.Value == 600842);
Assert.IsTrue(dateField.Value == default(DateTime));
}
这篇关于switch 语句:“需要一个常量值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!