- Feature introduced in C# 2.0
// Declare the generic class.
public class GenericList< t>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList< int> list1 = new GenericList< int>();
// Declare a list of type string.
GenericList< string> list2 = new GenericList< string>();
// Declare a list of type ExampleClass.
GenericList< exampleclass> list3 = new GenericList< exampleclass>();
}
}
class Test
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
// Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };
// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Hello. My name is M and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/
Nullable Type 可為 Null 的類型 (C# 程式設計手冊)
- 可為 Null 的型別是 System.Nullable<T> 結構的執行個體
- 可為 Null 的型別可以代表其基礎值型別的正確值範圍,再加上額外的 null 值
- Code
///
/// 使用 HasValue 成員先測試變數是否包含值,再嘗試顯示它
///
int? x = 10;
if (x.HasValue)
{
System.Console.WriteLine(x.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
///
/// 使用 null 成員先測試變數是否包含值,再嘗試顯示它
///
int? y = 10;
if (y != null)
{
System.Console.WriteLine(y.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
///
/// 明確轉換
///
int? n = null;
//int m1 = n; // Will not compile.
int m2 = (int)n; // Compiles, but will create an exception if n is null.
int m3 = n.Value; // Compiles, but will create an exception if n is null.
int? n = null;
int m = 0;
// 1. 一般判別
if ( n == null )
m = 0;
else
m = n;
// 2. (三元)運算子
// https://msdn.microsoft.com/zh-tw/library/zakwfxx4(v=vs.100).aspx
m = (n == null ? 0 : n);
// 3. null 聯合運算子
// https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/null-conditional-operator
m = n ?? n;
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
Covariance Contra variance 泛型中的共變數和反變數
- 因在 C# 4.0 版本有加強此方式的使用方法
- 此先不做討論
Ref:
- https://www.slideshare.net/ssusercab70d/c35-55576724
沒有留言:
張貼留言