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 ...
随机推荐
- Executors工厂类
newCachedThreadPool 重用之前的线程 适合执行许多短期异步任务的程序. 调用 execute() 将重用以前构造的线程 如果没有可用的线程,则创建一个新线程并添加到池中 默认为60s ...
- UVA - 10723 Cyborg Genes (LCS)
题目: 思路: 求两个串的最长公共子序列,则这个最短的串就是给出的两个串的长度和减去最长公共子序列的长度. 状态转移方程: 如果s[i-1]==t[j-1]就有dp[i][j] = dp[i-1][j ...
- UVA 674 Coin Change (完全背包)
解法 dp表示目前的种数,要全部装满所以f[0]=1其余为0的初始化是必不可少的 代码 #include <bits/stdc++.h> using namespace std; int ...
- python3返回值中的none
浏览器返回null,python3返回none,懵了. google了很多资料,不明就里,这就是没基础的后果啊呀呀呀. 上阮一峰的截图,就这么理解下凑合吧:
- hdu 5122(2014ACM/ICPC亚洲区北京站) K题 K.Bro Sorting
传送门 对于错想成lis的解法,提供一组反例 1 3 4 2 5同时对于这次案例也可以观察出解法:对于每一个数,如果存在比它小的数在它后面,它势必需要移动,因为只能小的数无法向右移动,而且每一次移动都 ...
- idea 快捷键设置
通过 点击放大镜然后按当前需要修改的快捷键找到需要修改的快捷键,更改成希望的快捷键
- 关于datanode多磁盘存储策略
目的: 节点内各存储磁盘均衡 相关参数: dfs.datanode.fsdataset.volume.choosing.policy=org.apache.hadoop.hdfs.server.dat ...
- Apache Maven Cookbook(八)学习笔记-Handling Typical Build Requirements
Including and excluding additional resources Using the Maven Help Plugin: mvn help:effective-pom mvn ...
- Python函数基础---参数、变量
函数:指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可. def sayhi( ): # 函数名 print('hello world') sayhi( ) # ...
- 【BZOJ3676&UOJ103】回文串(manacher,Trie)
题意:考虑一个只包含小写拉丁字母的字符串s.我们定义s的一个子串t的“出现值”为t在s中的出现次数乘以t的长度. 请你求出s的所有回文子串中的最大出现值. len<=300000 思路:鸣谢UO ...