Answer the question
In order to leave comments, you need to log in
How to deal with generic types?
I read an article about delegates. Everything seems to be clear, but there were generalized types that I didn’t fully understand. At an intuitive level, the connections in the code are clear, but ...
delegate T Operation<T, K>(K val);
class Program
{
static void Main(string[] args)
{
Operation<decimal, int> op = Square;
Console.WriteLine(op(5));
Console.Read();
}
static decimal Square(int n)
{
return n * n;
}
}
delegate T Operation<T, K>(K val);
<T, K>
? Well, it is clear that it indicates what types are used in the Operate delegate, but what is it called? Explain in Russian, please.
Answer the question
In order to leave comments, you need to log in
Generics are when you expect certain types to be used in a context and you need to bind them according to certain criteria. It also saves you the hassle of having to type cast later in your code.
As an example, task: You need to implement class A with property F, which can be any type implemented from interface IB:
Solution 1. Non-optimized approach without generics:
class A {
IB F { get; }
}
A a = new A();
C c = a.F as C; // Здесь придется приводить к типу.
class A<T> {
T F { get; }
}
A<C> a = new A<C>();
C c = a.F; // Здесь лежит сразу экземпляр типа C, приводить к типу не нужно.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question