从对象获取子类内容

时间:2017-08-02 12:45:44

标签: c#

我有以下课程

public enum Category { foo, foo1, foo2 }

public class Event
{

    public DateTime Timestamp { get; set; } = DateTime.Now;
    public string GameTime { get; set; }
    public string Content { get; set; }
    public Person Author { get; set; }
    public Category Category { get; set; }

}

public class MemberEvent : Event
{
    public Member Person { get; set; }                
}

正确创建了对象,但是如果我想调用“Person”,则不会向我显示。如果我有var match,我可以拨打match[0].Timestamp,但不能match[0].PersonEvent对象存储在List中,因此也存储在索引中。我觉得我错过了一些简单的事情。

更新:创建对象的代码

var match = SessionController.Instance.Current;

DataTable dt = dataGrid.ItemsSource as DataTable;

        foreach (System.Data.DataRow item in dt.Rows)
        {
                var memberFoo = new MemberEvent();
                memberFoo.Category = Category.Warning;
                memberFoo.Time = item["Time"].ToString();
                var person = new Person();
                person.FirstName = item["FirstName"].ToString();
                person.LastName = item["LastName"].ToString();
                var passport = new Passport();
                passport.Active = true;
                passport.PassNumber = item["Pass"].ToString();
                passport.Player = person;
                memberFoo.Person = passport;
                match.Match.Events.Add(memberFoo);             
        }

        SessionController.Instance.Current = match;

2 个答案:

答案 0 :(得分:0)

如果您想访问MemberEvent媒体资源,则必须将Person投放到Event。无法从List<Event> myEvents = GetMyEvents(); var myMemberEvent = (MemberEvent)myEvent[0]; 获取该属性。

MemberEvent

如果无法转换为PXLongOperation.StartOperation(this, delegate () ,则会导致异常。

答案 1 :(得分:0)

将您的实例转换为期望的类型并测试null以防范意外:

var memberEvent = match[0] as MemberEvent;
if (memberEvent != null)
{
   Console.WriteLine(memberEvent.Person)
}