📜  c# final - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:21.331000             🧑  作者: Mango

代码示例1
//c# doesn't have final however it has equivalent sealed, readonly, const
/**************************************************************/
//sealing a class
sealed class SealedClassA{ 
    public void testA(){Console.WriteLine("test A");}
}
//class childclass : SealedClassDemo { } -> will lead to an error
//A class which is marked by keyword sealed cannot be inherited.
/**************************************************************/
//sealing a method
class SealedClassA{ 
    public void testA(){Console.WriteLine("test A");}
}
class childclassB : SealedClassDemo { 
    public sealed override void testA(){Console.Write("test A B");}
}
//only methods with override can be sealed.
/**************************************************************/
//making a const
public const float x = 1.0f
// the value x can't be modified. 
/**************************************************************/
//making a readonly
public static readonly uint l1 = (uint) DateTime.Now.Ticks;
 /*The readonly keyword is different from the const keyword.
 A const field can only be initialized at the declaration of the field. 
 A readonly field can be initialized either at the declaration or in a constructor.
 Therefore, readonly fields can have different values depending on the constructor used.
*/