Thoughts on generic classes and extension methods
We often use generic constructors to create generic instances and call extension methods of instances. The following code is everywhere in the project:
static void Main(string[] args)
{
var strs = new List<string> {"hello","world"};
var result = strs.Where(s => s.StartsWith("h"));
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
Above,
● How is an instance created through the constructor of the generic set List <T> implemented internally?
● The Where method is used for the instance variable strs. We find that the Where method is smart enough because it is an extension method for the IEnumerable set type.
How is. NET implemented internally? Copy it ~~
Create a generic type.
public class MyCute<T>
{
public MyCute(T t)
{
GetCute = t;
}
public T GetCute { get; set; }
}
The following code is called on the client:
static void Main(string[] args)
{
var cuteInt = new MyCute<int>(10);
var cuteStr = new MyCute<string>("hello");
Console.WriteLine(cuteInt.GetCute);
Console.WriteLine(cuteStr.GetCute);
Console.ReadKey();
}
The above may be the inspiration: If you want to create a generic instance through the constructor, You need to define a generic class and a generic type attribute, A constructor that uses generic types as parameters.
What should I do if I want to use the extension method for the attributes of the generic instance cuteInt and cuteStr GetCute?
The GetCute attribute of cuteInt is of the int type, the GetCute attribute of cuteStr is of the string type, and the common base class of the two is object. Then, write an extension method for the object type.
public static class MyHelper
{
public static string GetStr(this object obj)
{
return obj.ToString() + "--added string";
}
}
The client becomes like this:
static void Main(string[] args)
{
var cuteInt = new MyCute<int>(10);
var cuteStr = new MyCute<string>("hello");
Console.WriteLine(cuteInt.GetCute.GetStr());
Console.WriteLine(cuteStr.GetCute.GetStr());
Console.ReadKey();
}
Summary:
● If the operation logic for different types is the same, a generic class can be abstracted. There is no essential difference between a generic class and a common class, except that a placeholder or type parameter is added after the class name. The constructor parameter of a generic class is a type parameter, the attribute type of a generic class is also a type parameter.
● If the operation logic for different types of instances is the same, you can write an extension method for the common parent class or interface of different instance types.