[英]How to access subclass variables through a reference of the superclass with C#
I have a User class which is my parent class.我有一个User类,它是我的父类。 and I have a SiteAdmin class which is inherited from User class:我有一个继承自User类的SiteAdmin类:
public abstract class User { }
public class SiteAdmin : User
{
public string ProfilePicUrl { get; set; }
}
The scenario is I want to check if an User instance is a type of SiteAdmin class, then access to SiteAdmin properties with User object.场景是我想检查User实例是否是SiteAdmin类的类型,然后使用User对象访问SiteAdmin属性。 Suppose ProfilePicUrl is a property of SiteAdmin class.假设ProfilePicUrl是SiteAdmin类的一个属性。 How can I access this propery with User object?如何使用User对象访问此属性?
if (comment.User is SiteAdmin)
{
var profilePicUrl = comment.User.ProfilePicUrl;
}
Try this:尝试这个:
if (comment.User is SiteAdmin siteAdmin)
{
var profilePicUrl = siteAdmin.ProfilePicUrl;
}
Or you could do this:或者你可以这样做:
if (comment.User is SiteAdmin)
{
var profilePicUrl = (comment.User as SiteAdmin).ProfilePicUrl;
}
您可以定义超类和子类之间的契约,例如抽象方法,在User
和SiteAdmin
实现抽象方法并返回ProfilePicUrl
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.