C# 创建适合所有类类型的变量
是否可以创建一个表示多个类对象的变量并调用该类中存在的函数? 我想创造这样的东西C# 创建适合所有类类型的变量,c#,class,C#,Class,是否可以创建一个表示多个类对象的变量并调用该类中存在的函数? 我想创造这样的东西 class A{ void DoSomething(){ //some code } } class B{ void DoSomething(){ //some code } } class Controller{ public ClassType theObject; public void DoSomething(){
class A{
void DoSomething(){
//some code
}
}
class B{
void DoSomething(){
//some code
}
}
class Controller{
public ClassType theObject;
public void DoSomething(){
theObject.DoSomething();
}
}
class Main{
public static void main(){
A objectA = new A();
B objectB = new B();
Controller objectC = new Controller();
objectC.theObject = objectA;
objectC.DoSomething();
objectC.theObject = objectB;
objectC.DoSomething();
}
}
有人知道怎么做吗(在class
Controller
中更改ClassType
的关键字是什么)或者我需要使用什么关键字来搜索类似的内容?我已经尝试让答案尽可能与您的代码相似。您所看到的称为接口。作为一个非常基本的解释,实现接口的类需要为接口中定义的每个方法提供代码。因此,通过多态性,您可以将一个具体类的实例,例如a
和B
分配给一个ClassType
,这是您的接口。然后,您可以调用接口中对当前分配的对象定义的任何方法
interface ClassType
{
void DoSomething();
}
class A : ClassType
{
void DoSomething()
{
//some code
}
}
class B : ClassType
{
void DoSomething()
{
//some code
}
}
class Main
{
public static void main()
{
A objectA = new A();
B objectB = new B();
ClassType objectC;
objectC = objectA;
objectC.DoSomething();
objectC = objectB;
objectC.DoSomething();
}
}
您可以创建并让类A和B实现它
interface ICanDoSomething {
void DoSomething();
}
class A : ICanDoSomething {
void DoSomething(){
//some code
}
}
class B : ICanDoSomething{
void DoSomething(){
//some code
}
}
class Controller {
public ICanDoSomething theObject;
public void DoSomething(){
theObject.DoSomething();
}
}
....
您正在寻找接口吗?