Professional Documents
Culture Documents
Generics in C# BG
Generics in C# BG
Generics in C# BG
Програма 1а
namespace GenericsDemo
{
public class ClsMain
{
private static void Main()
{
bool IsEqual = ClsCalculator.AreEqual(10, 20);
if (IsEqual)
{
Console.WriteLine("Both are Equal");
}
else
{
Console.WriteLine("Both are Not Equal");
}
Console.ReadKey();
}
}
public class ClsCalculator
{
public static bool AreEqual(int value1, int value2)
{
return value1 == value2;
}
}
}
[Дата]
1
2. Промяна на метод за да приема различни типове данни
Нека модифицираме метода AreEqual() на класа ClsCalculator, за да използваме
типа данни Object, както е показано по-долу
Програма 1б
namespace GenericsDemo
{
public class ClsMain
{
private static void Main()
{
// bool IsEqual = ClsCalculator.AreEqual(10, 20);
bool IsEqual = ClsCalculator.AreEqual("ABC", "ABC");
if (IsEqual)
{
Console.WriteLine("Both are Equal");
}
else
{
Console.WriteLine("Both are Not Equal");
}
Console.ReadKey();
}
}
public class ClsCalculator
{
//Now this method can accept any data type
public static bool AreEqual(object value1, object value2)
{
return value1 == value2;
}
}
}
Недостатъци:
Програма 2
namespace GenericsDemo
{
public class ClsMain
{
private static void Main()
{
// bool IsEqual = ClsCalculator.AreEqual(10, 20);
// bool IsEqual = ClsCalculator.AreEqual("ABC", "ABC");
bool IsEqual = ClsCalculator.AreEqual(10.5, 20.5);
[Дата]
2
if (IsEqual)
{
Console.WriteLine("Both are Equal");
}
else
{
Console.WriteLine("Both are Not Equal");
}
Console.ReadKey();
}
}
public class ClsCalculator
{
public static bool AreEqual(int value1, int value2)
{
return value1 == value2;
}
public static bool AreEqual(string value1, string value2)
{
return value1 == value2;
}
public static bool AreEqual(double value1, double value2)
{
return value1 == value2;
}}
}
[Дата]
3
За да направим метода AreEqual() шаблонен в горния пример, посочваме параметъра
на типа T, използвайки ъгловите скоби <T>. След това използваме този тип като тип
данни за параметрите на метода, както е показано на изображението по-долу.
[Дата]
4
Ако искате да работите със символни низове, методът AreEqual() се извиква както
следва:
bool IsEqual= ClsCalculator.AreEqual<string>(“ABC”, “ABC”);
4. Шаблонни класове
Нека създадем шаблонен клас с шаблонен конструктор, поле и свойство от
параметризиран тип и шаблонен метод, както е показано по-долу. Ще създадем
класа MyGenericClass с <T>. Ъгловите скоби (“<>”) показват, че класът
MyGenericClass е шаблонен клас и типът за този клас ще бъде дефиниран по-късно.
Програма 4
using System;
namespace GenericsDemo
{
//MyGenericClass is a Generic Class
class MyGenericClass<T>
{
//Generic variable
//The data type is generic
private T genericMemberVariable;
//Generic Constructor
//Constructor accepts one parameter of Generic type
public MyGenericClass(T value)
{
genericMemberVariable = value;
}
//Generic Method
//Method accepts one Generic type Parameter
//Method return type also Generic
public T genericMethod(T genericParameter)
{
Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),
genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(),
genericMemberVariable);
return genericMemberVariable;
}
//Generic Property
//The data type is generic
public T genericProperty { get; set; }
}}
class Program
{
static void Main()
{
MyGenericClass<int> integerGenericClass = new MyGenericClass<int>(10);
[Дата]
5
Изход:
[Дата]
6
Компилаторът ще компилира горния клас, както е показано на фигурата по-
долу:
При създаване на обект можем да използваме всеки тип според нашето изискване.
Ако искаме да използваме низов тип, тогава трябва да създадем обект, както е
показано по-долу.
Програма 5
using System;
namespace GenericsForStrings
{
class MyGenericClass<T>
{
private T genericMemberVariable;
public MyGenericClass(T value)
{
genericMemberVariable = value;
}
[Дата]
7
class Program
{
static void Main(string[] args)
{
MyGenericClass < string >stringGenericClass= new
MyGenericClass<string>("Hello Generic World!");
stringGenericClass.genericProperty = "This is generic property example.";
Console.ReadKey();
}
}
}
Изход:
Parameter type: System.String, value: Generic Parameter
Return type: System.String, value: Hello Generic World!
[Дата]
8