gpt4 book ai didi

C#多重继承

转载 作者:可可西里 更新时间:2023-11-01 08:14:50 26 4
gpt4 key购买 nike

目前我正在使用 Code First Approach 学习 C# 和 ASP.NET MVC 4。我是 Visual Basic 开发人员,现在我想启动 C#。而且,现在我遇到了必须管理多重继承的情况。但是,我认为 Class 是不可能的。那么,我应该如何管理我拥有的这些类(class):

//I have the Following Person Class which Hold Common Properties 
//and a Type of Person e.g : Student, Faculty, Administrative
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Type { get; set; }
}


//This is my Student Class, which is Derived from Person
public class Student : Person
{
public DateTime DateOfBirth { get; set; }
public DateTime EnrollmentDate { get; set; }
public string Remarks { get; set; }

public bool Approved { get; set; }
public DateTime ApprovedDate { get; set; }
public int ApprovedUserId { get; set; }
}


//This is my Faculty Class, which is also Derived from Person
public class Faculty : Person
{
public DateTime HiredDate { get; set; }

public bool Approved { get; set; }
public DateTime ApprovedDate { get; set; }
public int ApprovedUserId { get; set; }
}

我要制作的是 Approved,ApprovedDate 和 ApprovedUserId 也很常见。我想指定这些属性,例如:

 public class Approve {
public bool Approved { get; set; }
public DateTime ApprovedDate { get; set; }
public int ApprovedUserId { get; set; }
}

而且,想像这样使用:

public class Student : Person, Approve
{
public DateTime DateOfBirth { get; set; }
public DateTime EnrollmentDate { get; set; }
public string Remarks { get; set; }
}

而且,我不能把那些东西放在 PERSON 里面。因为,我必须将它用于另一个类,但那些不是 Person。

那么,我该如何实现...

请给我一个上述情况的例子。

请帮助。并且,非常感谢您。

最佳答案

一个可能的解决方案是修改您的层次结构:

public class PersonWithApprove : Person { // TODO: replace with non disgusting name
public bool Approved { get; set; }
// etc...
}

public class Student : PersonWithApprove {
}

public class Faculty : PersonWithApprove {
}

或者你可以创建一个接口(interface):

public interface IApprove {
bool Approved { get; set; }
// etc
}

public class Student : Person, IApprove {
}

您也可以保留 Approve 类,并让类具有该类型的属性:

public class Student : Person {
Approve _approve = new Approve();
public Approve Approve {
get { return _approve; }
}
}

关于C#多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18438196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com