继承相关的问题

时间:2010-10-07 12:33:47

标签: c#

我有一个班级基地。 A和B扩展Base。还有一个类关系,它包含两个Base对象(source,target)。是否可以确定源/目标是A还是B实例?

感谢。

基督教

PS:

这里有一点补充。我正在使用automapper,我想将源/目标的类型映射到一个名为'Type'的字符串 - GetType不起作用(实际上它起作用 - 就像我的评论一样 - 也是好的解决方案)< /强>:

Mapper.CreateMap<Item, ItemViewModel>()
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.ItemName == null ? "" : src.ItemName.Name))
                .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.GetType().ToString()));

我如何在这种情况下使用is / as?

3 个答案:

答案 0 :(得分:8)

烨:

if (source is A)

if (source is B)

或:

A sourceA = source as A;
if (sourceA != null)
{
   ...
}

有关更多指导,请参阅this question - 还有很多其他类似的指导。

答案 1 :(得分:4)

是肯定的。

if (source is B)...

答案 2 :(得分:0)

使用is运算符? :)