Generics: Use parameterized types to operate multiple data types on the same code. Use "parameterized types" to abstract types to achieve flexible reuse. Test
‐ ‐ .
Console.WriteLine(" String: " + test1.obj);
Console.Read(); Public T obj;
Public Test(T obj)
This.obj =
Program analysis:
1. Test is a generic class . T is the generic type to be instantiated. If T is instantiated as type int, then the member variable obj is of type int. If T is instantiated as type string, then obj is of type string.
2. Depending on the type, the above program displays different values.
C# generic mechanism:
C# generic capabilities are supported by CLR at runtime: When C# generic code is compiled into IL code and metadata, special placeholders are used to represent generic types, and special Some IL instructions support generic operations. The real generic instantiation work occurs in an "on-demand" manner during JIT compilation.
Look at the metadata of the Main function in the code just now
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 79 (0x4f)
.maxstack 2
.locals init ([0] int32 obj,
[1] class CSharpStudy1.Test`1
[2] string obj2,
[3] class CSharpStudy1.Test` 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: stloc.0
IL_0003: ldloc.0
IL_00 04: newobj instance void class CSharpStudy1.Test`1
IL_0009: stloc.1
IL_000a: ldstr "int:"
IL_000f: ldloc.1
IL_0010: ldfld !0 class CSharpStudy1. Test`1
IL_001a: call String [mSCORLIB] System.String :: Concat (object,
object)
IL_001F: call void [mscorlib] system.con.con sole :: writeline (string )
IL_0024: nop
IL_0025: ldstr "hello world"
IL_002a: stloc.2
IL_002b: ldloc.2
IL_002c: newobj instance void class CSharpStudy1.Test`1
IL_0031: stloc.3
IL_0032: ldstr "String:"
IL_0037: ldloc.3
IL_0038: ldfld !0 class CSharpStudy1.Test`1
IL_003d: call string [mscorlib]System.String::Concat(string,
string)
IL_0042: call void [mscorlib]System.Console::WriteLine(string)
IL_0047: nop
IL_0048: call int32 [mscorlib]System.Console::Read()
IL_004d: pop
IL_004e: ret
} // end of method Program::Main
再来看看Test类中构造函数的元数据
.method public hidebysig specialname rtspecialname
instance void .ctor(!T obj) cil managed
{
// Code size 17 (0x11)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: nop
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: stfld !0 class ConsoleCSharpTest1.Test`1::obj
IL_000f: nop
IL_0010: ret
} // end of method Test`1::.ctor
1、第一轮编译时,编译器只为Test
2、JIT编译时,当JIT编译器第一次遇到Test
3、CLR为所有类型参数为“引用类型”的泛型类型产生同一份代码;但是如果类型参数为“值类型”,对每一个不同的“值类型”,CLR将为其产生一份独立的代码。因为实例化一个引用类型的泛型,它在内存中分配的大小是一样的,但是当实例化一个值类型的时候,在内存中分配的大小是不一样的。
C#泛型特点:
1、如果实例化泛型类型的参数相同,那么JIT编辑器会重复使用该类型,因此C#的动态泛型能力避免了C++静态模板可能导致的代码膨胀的问题。
2、C#泛型类型携带有丰富的元数据,因此C#的泛型类型可以应用于强大的反射技术。
3、C#的泛型采用“基类、接口、构造器,值类型/引用类型”的约束方式来实现对类型参数的“显示约束”,提高了类型安全的同时,也丧失了C++模板基于“签名”的隐式约束所具有的高灵活性
C#泛型继承:
C#除了可以单独声明泛型类型(包括类与结构)外,也可以在基类中包含泛型类型的声明。但基类如果是泛型类,它的类型要么以实例化,要么来源于子类(同样是泛型类型)声明的类型参数,看如下类型
class C
class D:C
class E:C
class F:C
class G:C //非法
E类型为C类型提供了U、V,也就是上面说的来源于子类
F类型继承于C
G类型为非法的,因为G类型不是泛型,C是泛型,G无法给C提供泛型的实例化
Members of generic types:
Members of generic types can use type parameters in the generic type declaration. But if the type parameter does not have any constraints, you can only use public members inherited from System.Object on the type. As shown below:
Generic interface:
The type parameters of the generic interface are either instantiated or derived from the type parameters declared by the implementation class
Generic delegate:
Generic delegate supports delegation Parameter types are applied to the return value and parameters. These parameter types can also come with legal constraints
delegate bool MyDelegate
class MyClass
{
static bool F(int i){.. .}
static bool G(string s){...}
static void Main()
{
MyDelegate
MyDelegate
}
}
Generic methods:
1. The C# generic mechanism only supports "containing type parameters on the method declaration" - that is, generic methods.
2. The C# generic mechanism does not support the inclusion of type parameters in the declaration of other members (including properties, events, indexers, constructors, destructors) except methods, but these members themselves can be included in the generic type , and use type parameters of generic types.
3. Generic methods can be included in both generic types and non-generic types.
Generic method declaration: as follows
public static int FunctionName
Overload of generic method:
public void Function1
public void Function1(U a);
This cannot constitute an overloading of a generic method. Because the compiler cannot determine whether the generic types T and U are different, it cannot determine whether the two methods are different
public void Function1
public void Function1(int x);
This can constitute an overload
public void Function1
public void Function1
This cannot constitute a generic method of overloading. Because the compiler cannot determine whether A and B in the constraints are different, it cannot determine whether the two methods are different.
Generic method rewriting:
In the process of rewriting, the abstract method in the abstract class constraints are inherited by default. As follows:
abstract class Base
{
public abstract T F
public abstract T G
}
class MyClass:Base
{
public override ) where T:IComparable{}
}
For the two overridden methods in MyClass
F method is legal, constraints are inherited by default
G method is illegal, specifying any constraints is redundant
Generic constraints:
1. C# generics require that any assumptions about "type parameters of all generic types or generic methods" must be based on "explicit constraints" to maintain the requirements required by C# Type safety.
2. "Explicit constraints" are expressed by where clauses, and you can specify four types of constraints: "base class constraints", "interface constraints", "constructor constraints", and "value type/reference type constraints".
3. "Explicit constraints" are not required. If "explicit constraints" are not specified, generic type parameters will only be able to access public methods in the System.Object type. For example: In the initial example, the obj member variable is defined. For example, we add a Test1 class to the initial example and define two public methods Func1 and Func2 in it, as shown below:
Let’s start analyzing these constraints:
Base class constraints:
class A
public void Func1 Func2()
T//S’s variable can call the Func1 method
s.Func1();
//T’s variable can call the Func2 method
t.Func2();
. }
Interface constraints:
interface IA
}
interface IC
{
T Func3();
}
class MyClass
where T : IA
where V : IB, IC
{
public MyClass(T t, V v)
// The object of T can call Func1
t.Func1(); v.Func2();
v.Func3() );
}
}
Constructor constraint:
class A
,,,,,,,,,,,,,,,,,,,,,,,,, )
public C()
}
} l class d
{
public void func () {
c & lt; a & gt; c = new c & lt; a & gt; (); ; B & GT; ();}}}}
D Object Error: The Type B Must has have a public parameterless constructor in order to use it as Parameter 'in the GENERIC TYPE OR METHOD C & lt; t & gt;
Note: C# now only supports parameterless constructor constraints
At this time, since we have written a parameterized constructor for type B, the system will no longer automatically create a parameterless constructor for B, but if We add a parameterless constructor to type B, so the instantiation of object d will not report an error. The B type is defined as follows:
class B
{
public B() Type/reference type:
public struct A { }
public class B { }
public class C
;
C c2 = new C
The c2 object gets an error when compiling: The type 'B' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or methor 'C
Summary:
1. C#'s generic capabilities are supported by the CLR at runtime. It is different from the static templates supported by C++ at compile time, and also different from the simple "wiping method" supported by Java at the compiler level. of generics.
2. C#’s generic support includes four generic types: classes, structures, interfaces, delegates, and method members.
3. C#'s generics use the constraint method of "base class, interface, constructor, value type/reference type" to implement "explicit constraints" on type parameters. It does not support implicit signature-based constraints like C++ templates. formula constraints.
The above is the content of C# generic programming. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
