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.

http://stackoverflow.com/questions/5709034/does-c-sharp-support-return-type-covariance/5709191#5709191

问题:

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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords

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)的更多相关文章

  1. 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 ...

  2. 【转载】#273 - Parameter Modifier Summary

    Here's a summary of the different parameter modifiers and how the behavior changes for each, when us ...

  3. 解决Deprecated: preg_replace(): The /e modifier is deprecated, use

    使用php5.5运行ecshop的时候出现如下错误Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace ...

  4. Java Interview Reference Guide--reference

    Part 1 http://techmytalk.com/2014/01/24/java-interview-reference-guide-part-1/ Posted on January 24, ...

  5. 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 ...

  6. 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 ...

  7. What the difference between __weak and __block reference?

    近日遇到一个非常细的知识点,关于block的循环引用问题.相比非常多人都遇到了.也能顺利攻克了,至于block方面的技术文章.那就很多其它了.这里不再赘述,可是有这样一个问题: What the di ...

  8. abstract (C# Reference)

    https://msdn.microsoft.com/en-us/library/sf985hc5.aspx The abstract modifier indicates that the thin ...

  9. protected (C# Reference)

    https://msdn.microsoft.com/en-us/library/bcd5672a.aspx The protected keyword is a member access modi ...

随机推荐

  1. JMeter在linux上分布式压测遇到的坑(三)

    master和slave机要在同一网段内,才能做分布式(Jmeter要配环境变量,这样不用手动起server) 分布式不成功,解决方案: 1.master端和slave端要ping通 2.ping通后 ...

  2. angularJs 解析factory、service、provider

    了解angular js factory可以认为是设计模式中的工厂方法,就是你提供一个方法,该方法返回一个对象的实例:对于angularJs的factory,就是先定义一个对象,给这个对象添加属性和方 ...

  3. 支持向量机(SVM)原理浅析

    因为网页博客输入公式很麻烦,所以就在word上面写了,然后截图发上来. 后续关于SVM和FC在深度学习当中得使用对比分析,我再补充.

  4. 关于C++中字符串输入get与getline的区别

    最近使用C++中自己老是忘记的一个点,get与getline的区别. 1.get与getline get和getline所属iostream类,作用是读取一整行,通过换行符确定读取结束,他们都可以读取 ...

  5. 利用stylist插件,简单两步屏蔽新浪微博上的广告

    以前新浪微博只是在侧栏有几块小小的广告,还算可以接受,想着忍忍就算了,可最近真是越来越不厚道了,自从和淘宝合作之后,侧栏就开始有一大块广告根据你在淘宝的搜索记录推荐商品,更可恶的是信息流里的祛痘微博现 ...

  6. [模拟赛FJOI Easy Round #2][T1 sign] (模拟+求字符串重复字串)

    [题目描述] 小Z在无意中发现了一个神奇的OJ,这个OJ有一个神奇的功能:每日签到,并且会通过某种玄学的算法计算出今日的运势.在多次试验之后,小Z发现自己的运势按照一定的周期循环,现在他找到了你,请通 ...

  7. ModelMap org.springframework.ui.ModelMap

    ModelMap实现了map接口,可以在其中存放属性,作用域同request,同时可与@SessionAttributes联合使用,把数据放入到session中去, 下面这个示例,我们可以在Model ...

  8. POJ 1655 Balancing Act && POJ 3107 Godfather

    题目大意: 根据题目的图很好理解意思,就是记录每一个点的balance,例如 i 的balance就是把 i 从这棵树中除去后得到的森林中含有结点数最多 的子树中的节点个数,然后找到所有节点中对应的b ...

  9. BZOJ2521 最小生成树 最小割

    5.26 T2:最小生成树 Description Secsa最近对最小生成树问题特别感兴趣.他已经知道如果要去求出一个n个点.m条边的无向图的最小生成树有一个Krustal算法和另一个Prim的算法 ...

  10. 采药 2005年NOIP全国联赛普及组&疯狂的采药

     时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题目描述 Description 辰辰是个天资聪颖的孩子,他的梦想是成为世界上最伟大的医师.为此,他想拜附近最有威望 ...