new Modifier (C# Reference)
https://msdn.microsoft.com/en-us/library/435f1dw2.aspx
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class.
When you hide an inherited member, the derived version of the member replaces the base class version.
Although you can hide members without using the new modifier, you get a compiler warning.
If you use new to explicitly hide a member, it suppresses this warning.
To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword.
For example:
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
In this example, BaseC.Invoke is hidden by DerivedC.Invoke.
The field x is not affected because it is not hidden by a similar name.
Name hiding through inheritance takes one of the following forms:
Generally, a constant, field, property, or type that is introduced in a class or struct hides all base class members that share its name.
There are special cases.
For example, if you declare a new field with name N to have a type that is not invocable, and a base type declares N to be a method, the new field does not hide the base declaration in invocation syntax.
See the C# language specification for details (see section "Member Lookup" in section "Expressions").
It is an error to use both new and override on the same member, because the two modifiers have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.
Using the new modifier in a declaration that does not hide an inherited member generates a warning.
问题:
I'm working with the .NET framework and I really want to be able to make a custom type of page that all of my website uses.
The problem comes when I am trying to access the page from a control.
I want to be able to return my specific type of page instead of the default page.
Is there any way to do this?
public class MyPage : Page
{
// My own logic
} public class MyControl : Control
{
public MyPage Page { get; set; }
}
答案:
It sounds like what you want is return type covariance. C# does not support return type covariance.
Return type covariance is where you override a base class method that returns a less-specific type with one that returns a more specific type:
class Animal
{
} class Fish : Animal
{
} abstract class Enclosure
{
public abstract Animal Contents();
}
class Aquarium : Enclosure
{
public new Fish Contents() { return new Fish(); }
}
This is safe because consumers of Contents via Enclosure expect an Animal, and Aquarium promises to not only fulfill that requirement, but moreover, to make a more strict promise: that the animal is always a fish.
//上面的代码会报错,因为返回类型不一致
This kind of covariance is not supported in C#, and is unlikely to ever be supported.
It is not supported by the CLR. (It is supported by C++, and by the C++/CLI implementation on the CLR; it does so by generating magical helper methods of the sort I suggest below.)
(Some languages support formal parameter type contravariance as well -- that you can override a method that takes a Fish with a method that takes an Animal. Again, the contract is fulfilled; the base class requires that any Fish be handled, and the derived class promises to not only handle fish, but any animal. Similarly, C# and the CLR do not support formal parameter type contravariance.)
The way you can work around this limitation is to do something like:
class Animal
{
} class Fish : Animal
{
} abstract class Enclosure
{
protected abstract Animal GetContents(); //子类通过重写这个方法,来返回Fish实例 public Animal Contents()
{
return this.GetContents();
}
}
class Aquarium : Enclosure
{
protected override Animal GetContents()
{
return this.Contents();
} public new Fish Contents()
{
return new Fish();
}
}
Now you get both the benefits of overriding a virtual method, and getting stronger typing when using something of compile-time type Aquarium.
Enclosure enclosure = new Aquarium();
Animal animal = enclosure.Contents();
Console.WriteLine(animal.GetType());
===2017年06月30日===更新
https://dotnetfiddle.net/tXdyiG
using System; namespace PolymorphismApplication
{
public abstract class Shape
{
protected int width, height;
public Shape(int a = , int b = )
{
width = a;
height = b;
} public virtual int area()
{
Console.WriteLine("Parent class area :");
return ;
} public virtual int func()
{
return ;
}
} public class Rectangle : Shape
{
public Rectangle(int a = , int b = ): base (a, b)
{
} public override int area()
{
Console.WriteLine("Rectangle class area :");
return (width * height);
} public new int func()
// if this class is implemented by an object declared on the base class
// e.g Shape newShape = new Rectancle(5, 10), then the object (newShape)
// will NOT inherit this method. It will stick to the one in Shape.
// Look at the implementation of Caller and the Program/Main to see example.
{
return ;
}
} public class Triangle : Shape
{
public Triangle(int a = , int b = ): base (a, b)
{
} public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / );
} public override int func()
{
return ;
}
} public class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
int c = sh.func();
Console.WriteLine("func: {0}", c);
}
public void CallArea2 (Rectangle rect)
{
int a;
a = rect.area();
Console.WriteLine("Area: {0}", a);
int c = rect.func();
Console.WriteLine("func: {0}", c);
}
} public class Program
{
public void Main(string[] args)
{
Caller c = new Caller();
c.CallArea(new Rectangle(, )); // a rectangle is being passed to CallArea's SHAPE object-variable sh
c.CallArea(new Triangle(, ));
c.CallArea2(new Rectangle(, )); // a rectangle is being passed to CallArea2's RECTANGLE object-variable rect
// Takeaway: When you declare a rectangle as a reactangle, it will act differently from when you declare it as a shape.
// And this is because of the use of 'new' for the func method, which is only given to rects declared as Rectangles
// }
}
}
https://github.com/kerryjiang/IrvineCSharpCourses/blob/master/Example11/Program.cs
new Modifier (C# Reference)的更多相关文章
- Knowing When to Use Override and New Keywords (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms173153.aspx In C#, a method in a derived class can have t ...
- 【转载】#273 - Parameter Modifier Summary
Here's a summary of the different parameter modifiers and how the behavior changes for each, when us ...
- 解决Deprecated: preg_replace(): The /e modifier is deprecated, use
使用php5.5运行ecshop的时候出现如下错误Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace ...
- Java Interview Reference Guide--reference
Part 1 http://techmytalk.com/2014/01/24/java-interview-reference-guide-part-1/ Posted on January 24, ...
- Sphinx 2.2.11-release reference manual
1. Introduction 1.1. About 1.2. Sphinx features 1.3. Where to get Sphinx 1.4. License 1.5. Credits 1 ...
- C# to IL 6 Reference and Value Types(引用类型和值类型)
An interface is a reference type, in spite of the fact that it has no code at all. Thus, wecannot in ...
- What the difference between __weak and __block reference?
近日遇到一个非常细的知识点,关于block的循环引用问题.相比非常多人都遇到了.也能顺利攻克了,至于block方面的技术文章.那就很多其它了.这里不再赘述,可是有这样一个问题: What the di ...
- abstract (C# Reference)
https://msdn.microsoft.com/en-us/library/sf985hc5.aspx The abstract modifier indicates that the thin ...
- protected (C# Reference)
https://msdn.microsoft.com/en-us/library/bcd5672a.aspx The protected keyword is a member access modi ...
随机推荐
- swift Enumerations
swift Enumerations enum.case.switch CaseIterable allCases 要区别枚举变量和关联值 枚举变量参与枚举运算: 关联值和rawvalue不参与. A ...
- 运行容器出现docker: Error response from daemon: driver failed programming external connectivity on endpoint elegant_ptolemy (7fe85ca6bd744449ff82b81c1577d73b6821c4e51780c8238fad6aa0cb940522): (iptables fai
运行容器时出现以下报错: docker: Error response from daemon: driver failed programming external connectivity on ...
- c++通过CMake实现debug开关
刚学cmake,很多东西还不是很懂,不过今天刚刚实现了通过CMake控制debug的开关,兴奋之余记录一下. 背景介绍: 最近参与到了一个大的C++项目,很多代码已经非常成熟,我来添加一些辅助功能,但 ...
- 11servlet接口
11.servlet接口-2018/07/23 1.servlet 是一个接口,需要导包javax.servlet.Servlet; 第一种编写一个servlet程序的方法 写一个Java类,实现se ...
- [Python数据结构] 使用 Circular List实现Queue
[Python数据结构] 使用 Circular List实现Queue 1. Queue队列,又称为伫列(queue),是先进先出(FIFO, First-In-First-Out)的线性表.在具体 ...
- ubuntu解压zip文件出现乱码情况解决方法
使用 unzip datastructure.zip 出现下面的情况: extracting: └╧╗╞/╗·╞ў╤з╧░╝п╜ї/╩¤╛▌╜с╣╣╙ы╦у╖и/╩¤╛▌╜с╣╣╙ы╦у╖иги2гй ...
- MyBatis 的基本要素—核心对象
MyBatis 三个基本要素 ➢ 核心接口和类 ➢ MyBatis 核心配置文件(mybatis-config.xml) ➢ SQL 映射文件(mapper.xml) MyBatis 核心接口和类 ...
- Jenkins 的插件AnsiColor 多颜色
- react入门-----(jsx语法,在react中获取真实的dom节点)
1.jsx语法 var names = ['Alice', 'Emily', 'Kate']; <!-- HTML 语言直接写在 JavaScript 语言之中,不加任何引号,这就是 JSX 的 ...
- 3.5.6 关系和boolean运算符
Java包含丰富的关系运算符.要检测相等性,可以使用两个等号 == .例如, 3 == 7 的值为 false. 另外可以使用 != 检测不相等.例如, 3 ! = 7 的值 ...