我有情况下,我给了一个对象的集合,这些对象都来自同一个基类。如果我遍历集合并检查每个项目的类型,我可以看到该对象是派生类型,然后相应地处理它。我想知道的是,除了我已经在做的事之外,是否还有更简单的方法来执行派生类型的检查。代码重复通常不是必需的,所以我目前的方法对我来说似乎有点偏离。可以在没有为基类类型的每个派生类类型进行类型转换的情况下再次降级上传的对象?
class A {}
class B : A {}
class C : A {}
class D : C {}
class Foo
{
public List<A> Collection { get; set; }
}
class Bar
{
void Iterate()
{
Foo f = new Foo();
foreach(A item in f.Collection)
{
DoSomething(a);
}
}
void DoSomething(A a)
{
...
B b = a as B;
if(b != null)
{
DoSomething(b);
return;
}
C c = a as C;
if(c != null)
{
DoSomething(c);
return;
}
D d = a as D;
if(d != null)
{
DoSomething(d);
return;
}
};
void DoSomething(B a){};
void DoSomething(C a){};
void DoSomething(D a){};
}
我与web服务,每一个Web服务必须具有相同的结果类型的工作。
class WebServiceResult
{
public bool Success { get; set; }
public List<Message> Messages { get; set; }
}
class Message
{
public MessageType Severity { get; set; } // Info, Warning, Error
public string Value { get; set; } //
}
class InvalidAuthorization: Message
{
// Severity = MessageType.Error
// Value = "Incorrect username." or "Incorrect password", etc.
}
class InvalidParameter: Message
{
// ...
}
class ParameterRequired: InvalidParameter
{
// Severity = MessageType.Error
// Value = "Parameter required.", etc.
public string ParameterName { get; set; } //
}
class CreatePerson: Message
{
// Severity = MessageType.Info
// Value = null
public int PersonIdentifier { get; set; } // The id of the newly created person
}
目标是我们可以根据需要返回尽可能多的不同类型的消息给客户端。每个Web服务调用都不会收到单个消息,被调用者可以在单次旅程中了解其所有错误/成功信息,并从消息中消除字符串解析特定信息。
我最初虽然关于使用泛型,但由于Web服务可能具有不同的消息类型,因此集合被扩展为使用基类消息类。
你究竟在努力实现什么?我问的原因是,你的方式闻起来像一个反模式。当你不得不用这种方式施展时,这通常是一个不好的迹象。查看Liskov替换原则(http://en.wikipedia.org/wiki/Liskov_substitution_principle) –
我编辑了这个问题来解释我的总体目标。 – JWilliams