类型专业化;如何确定每种特定类型并做出反应?
想象一下我有一个通用类Person
。然后我有该类的专业化,例如 DanishPerson
和 BritishPerson
。
现在我需要一个函数来返回正确的 Person 实例,具体取决于他们所在的国家/地区,或者一种轻松确定他们是什么类型的人的方法。所以我有这样的功能:
List<Person> GetPersonsByCountry(int countryId)
{
// query database, and get list of Persons in that country using EF inheritance
// return list of persons
}
人员列表,包含 DanishPerson
或 BritishPerson
类型的对象。根据类型,我需要在 UI 中显示正确的 ViewModel。因此,如果列表包含 DanishPerson
类型的丹麦人,我需要显示一个 UI 来显示丹麦人的特定属性(以及更多)。
现在我的问题是你如何以最好的方式做到这一点?我想我总是可以使用 typeof
来使用 if/else,但我希望有一种更优雅,也许通用的方式? 我在想,这样做可能有一些模式,因为在处理专业化时,这对我来说似乎是一个常见问题?
Imagine that I have a general class Person
. Then I have specializations of that class, for example DanishPerson
and BritishPerson
.
Now I need a function that returns the correct instance of Persons, depending on what country they are in, or a way to easily determine what type of persons they are. So I have the function:
List<Person> GetPersonsByCountry(int countryId)
{
// query database, and get list of Persons in that country using EF inheritance
// return list of persons
}
The list of persons, contains objects that are either of type DanishPerson
or BritishPerson
. Depending on the type, I need to display the right ViewModel in my UI. So if the list contains danish persons of type DanishPerson
, I need to display one UI that will show the danish specific properties (and more).
Now my question is how you do this the best way? I guess that I could always use an if/else using typeof
, but I was hoping for a more elegant, and maybe generic way?
I was thinking that there might be some patterns for doing this as it seems like a common problem to me, when dealing with specializations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Dictionary
来存储国家/地区代码和关联类类型之间的映射,然后使用 LINQ 方法OfType
来仅获取与所提供的国家/地区代码关联的类型。You could use a
Dictionary<K, V>
to store the mappings between the country codes and the associated class type and then use LINQ methodOfType
to obtain just the instances of the type associated to the provided country code.您可以使用字典根据人员类型映射行为。
更好的是创建一个 Ibehaviour 接口并从中继承两个类,一个用于英国,一个用于丹麦,并封装两者之间的不同行为。
当添加另一个人类型时,需要创建一个行为类并更新字典。
创建字典(类的私有成员):
代码中:
You can use Dictionary to map behaviour according to the person type.
Better yet create a Ibehaviour interface and inherit two classes from it one for British and one for Danish and encapsulate the different behaviour between the two.
When adding another person type requires creating a behaviour class and updating the Dictionary.
Create a dictionary (private member of the class):
In the code:
如果 List 对象是同质的(即它总是只填充丹麦人或英国人对象,那么这个小 LINQ 花絮将起作用:
If the List object is homogenous (i.e it's always either populated with only Danish or British person objects then this little LINQ tidbit will work: