调制检查并转换为值
Modulate a check and cast to value
我是 C# 的初级开发人员,遇到了一个相当不寻常的问题。现在,虽然我的代码目前按预期工作,但我希望有更好的方法来实现它。有问题的代码在我列表的 ForEach
中。这两个例子类继承了Example。我希望有更好的方法以更可重用的方式(方法)检查和执行以下代码,因为我在代码的其他地方使用了此类检查和应用程序。
public interface Example
{
// some stuff
}
public class Something
{
public List<Example> keybind ... // instantiate
public Something()
{
keybind.ForEach(b =>
{
// these checks are what I want to reuse
if (b.GetType() == typeof(Example1)
(b as Example1).Value = // new value
if (b.GetType() == typeof(Example2)
(b as Example2).Value = // new value
}
}
}
那么根本就不要进行检查 - 这就是接口的用途。如果你在你的接口中定义了一个 属性 Value
那么任何实现该接口的 class 都需要实现那个 属性 并且反过来消除了转换的需要完全没有。
public interface Example
{
string Value { get; set; }
}
public class Something
{
public List<Example> keybind... // instantiate
public Something()
{
keybind.ForEach(b =>
{
b.Value = // new value
}
}
}
如果您确实需要检查类型,那么您的语法是正确的,我建议的更好的替代方案如下(C# 7.0 的一部分):
if (b is Example1 ex1)
{
//do stuff
}
我是 C# 的初级开发人员,遇到了一个相当不寻常的问题。现在,虽然我的代码目前按预期工作,但我希望有更好的方法来实现它。有问题的代码在我列表的 ForEach
中。这两个例子类继承了Example。我希望有更好的方法以更可重用的方式(方法)检查和执行以下代码,因为我在代码的其他地方使用了此类检查和应用程序。
public interface Example
{
// some stuff
}
public class Something
{
public List<Example> keybind ... // instantiate
public Something()
{
keybind.ForEach(b =>
{
// these checks are what I want to reuse
if (b.GetType() == typeof(Example1)
(b as Example1).Value = // new value
if (b.GetType() == typeof(Example2)
(b as Example2).Value = // new value
}
}
}
那么根本就不要进行检查 - 这就是接口的用途。如果你在你的接口中定义了一个 属性 Value
那么任何实现该接口的 class 都需要实现那个 属性 并且反过来消除了转换的需要完全没有。
public interface Example
{
string Value { get; set; }
}
public class Something
{
public List<Example> keybind... // instantiate
public Something()
{
keybind.ForEach(b =>
{
b.Value = // new value
}
}
}
如果您确实需要检查类型,那么您的语法是正确的,我建议的更好的替代方案如下(C# 7.0 的一部分):
if (b is Example1 ex1)
{
//do stuff
}