为什么在继承中调用固定数据类型参数的对象class参数方法linseed
Why call object class parameter method linseed of fixed data type parameter in inheritance
案例一:
public class BaseClass
{
public virtual void Print(int i)
{
Console.WriteLine("BaseClass Print(int)");
}
}
public class DerivedClass : BaseClass
{
public override void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
DerivedClass objDerivedClass = new DerivedClass();
int i = 10;
objDerivedClass.Print(i);
}
输出为 DerivedClass Print(object)
.
案例二:
public class SomeClass
{
public void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
SomeClass objSomeClass = new SomeClass();
int i = 10;
objSomeClass.Print(i);
}
输出为 DerivedClass Print(int)
。
调用objDerivedClass.Print(i);
方法后,输出为DerivedClass Print(object)
。我不明白为什么调用方法 Print(object obj)
而不是 Print(int i)
.
如果DerivedClass
不继承BaseClass
class则输出为DerivedClass Print(int)
.
请解释......
这是重载解析如何与继承一起工作:
- 包含
override
修饰符的函数已从候选集中排除。
- 既然可以使用带
object
参数的函数,那么将在base中声明的函数从候选集合中移除。
获胜者是带有 object
参数的函数。
根据Eric Lippert (from Microsoft):
This is by design and for a good reason. This design helps prevent the Brittle Base Class problem. C# was designed to make it easier and safer to write "versioned" components, and this rule is a big part of that.
当不使用继承时,两个函数都是候选的,使用更具体的那个。获胜者是带有 int
参数的函数。
案例一:
public class BaseClass
{
public virtual void Print(int i)
{
Console.WriteLine("BaseClass Print(int)");
}
}
public class DerivedClass : BaseClass
{
public override void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
DerivedClass objDerivedClass = new DerivedClass();
int i = 10;
objDerivedClass.Print(i);
}
输出为 DerivedClass Print(object)
.
案例二:
public class SomeClass
{
public void Print(int i)
{
Console.WriteLine("DerivedClass Print(int)");
}
public void Print(object obj)
{
Console.WriteLine("DerivedClass Print(object)");
}
}
static void Main(string[] args)
{
SomeClass objSomeClass = new SomeClass();
int i = 10;
objSomeClass.Print(i);
}
输出为 DerivedClass Print(int)
。
调用objDerivedClass.Print(i);
方法后,输出为DerivedClass Print(object)
。我不明白为什么调用方法 Print(object obj)
而不是 Print(int i)
.
如果DerivedClass
不继承BaseClass
class则输出为DerivedClass Print(int)
.
请解释......
这是重载解析如何与继承一起工作:
- 包含
override
修饰符的函数已从候选集中排除。 - 既然可以使用带
object
参数的函数,那么将在base中声明的函数从候选集合中移除。
获胜者是带有 object
参数的函数。
根据Eric Lippert (from Microsoft):
This is by design and for a good reason. This design helps prevent the Brittle Base Class problem. C# was designed to make it easier and safer to write "versioned" components, and this rule is a big part of that.
当不使用继承时,两个函数都是候选的,使用更具体的那个。获胜者是带有 int
参数的函数。