作为一个DotNet程序员,你的DotNet技术硬不硬决定了你的饭碗如何。说实在DotNet技术具体是哪些,我也只能说个大概,C#,ASP.Net这都是些基本。像CLR当你工作一两年也必须了解的。楼主在学习SharePoint的同时,也准备好好看下DotNet的知识点。那我们的DotNet之旅先从C#开始,因为发现自己对于C#很多的Keywords都不是很熟悉,就先从Keywords开始,像某资深DotNet开发人员说,如果你把C#的Keywords都搞清楚了,那你的C#便掌握的百分之七八十。
abstract
abstract 可以修饰类,方法,属性,索引和事件,它所修饰的类一定要被这个抽象类派生出的类实现。先看看具体的例子:
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
abstract class BaseClass // Abstract class
{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod(); // Abstract method public abstract int X { get; }
public abstract int Y { get; }
}
class DerivedClass : BaseClass
{
public override void AbstractMethod()
{
_x++;
_y++;
}
public override int X // overriding property
{
get
{
return _x + 10;
}
}
public override int Y // overriding property
{
get
{
return _y + 10;
}
}
static void Main()
{
DerivedClass o = new DerivedClass();
o.AbstractMethod();
Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
}
}
// Output: x = 111, y = 161
这段代码是msdn上的,本身也运行过。在这里也提供一个学习的网站 http://msdn.microsoft.com/en-us/library/x53a06bb.aspx ,我也正在通过这个学习。
对于abstract的理解, 修饰方法时实际上是虚函数,这样用static或者virtual关键字修饰抽象方法很明显就不对了。抽象方法必须在抽象函数里,用abstract修饰静态属性也是不对的。抽象方法和抽象属性都可以被重写,加上关键字override。abstract 和sealed刚好相反,一个允许继承,一个不能被继承,之后也会进一步了解sealed。当然,抽象类是不能被实例化的,这点上我认为也许是抽象类的构造函数有问题?
BaseClass bc = new BaseClass(); // Error
关于abstract class和interface的区分从学java到现在也一直纠结着,在这里关于C#中的区别做一个总结:
1.interface 不能包含方法实现,abstract class可以包含也可以不包含。
2.interface只能继承interface,abstract class可以继承class或者一个或多个interface
3.interface不能包含字段,可以包含属性,abstract class 都可以包含(关于字段和属性的区别,希望会在之后的文章涉及)
4.interface不能包含构造和析构函数, abstract class都可以
5.interface支持多继承,abstract class不支持多继承(这让我想起了Diamond Problem,C++中解决了)??
as
第一次看到as关键字还是觉得很陌生的,as操作符就像转化操作,如果不是对应的类型就会返回null而不是抛出异常,用法如下:
expression as type
等价于 expression is type ? (type) expression :(type)null
下面是代码用例:
class Program
{
static void Main(string[] args)
{
object[] obs = new object[3];
obs[0] = new Program();
obs[1] = "Hello DotNet!";
obs[2] = null;
for (int i = 0; i < obs.Length; i++)
{
string s = obs[i] as string;
if (s != null)
{
Console.WriteLine("{0}:{1} is the type of string",i,s);
}
else {
Console.WriteLine("{0}:{1} is not type of string",i,s);
}
}
}
}
// Output:
//0: is not type of string
//1:Hello DotNet! is the type of string
//2: is not type of string
这些只是我根据MSDN上的再加上自己的理解,目的是为了让自己记得更深刻,当然也方便他人。事无巨细,本篇博客到此为止,下回继续,如有勘误,欢迎指正。