c#泛型类关键字

1.默认值default

default关键字根据上下文可以有多种含义。在泛型中,根据泛型类型是引用类型还是值类型,泛型default用于将泛型类型初始化为null或0.

2.约束

如果泛型类需要调用泛型类型中的方法,必须添加约束。where字句指定接口,where字句的一个重要限制就是,不能定义必须由泛型类型实现的运算符。运算符不能再借口中定义。在where子句中,只能定义基类、借口和默认构造函数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication3
{ 
    public class DocumentManager<TDocument>where TDocument:IDocument
    {
        private readonly Queue<TDocument> documentQueue = new Queue<TDocument>();

        public void AddDocument(TDocument doc)
        {
            lock (this)
            {
                documentQueue.Enqueue(doc);
            }
        }

        public bool IsDocumentAvailable
        {
            get { return documentQueue.Count > 0; }
        }

        public TDocument GetDocument()
        {
            TDocument doc = default(TDocument);
            lock (this)
            {
                doc = documentQueue.Dequeue();
            }
            return doc;
        }
        public void DisplayAllDocuments()
        {
            foreach (TDocument doc in documentQueue)
            {
                Console.WriteLine(doc.Title);
            }
        }
    }

    public interface IDocument
    {
        string Title { get; set; }
        string Content { get; set; }
    }

    public class Document : IDocument
    { 
        public Document()
        {
        }
          public Document(string title,string content)
        {
             this.Title = title;
             this.Content = content;
        }

        public string Title{get;set;}
        public string Content{get;set;}
       
    }

    public class AA
    {
        public static void Main() 
        {
            var dm = new DocumentManager<Document>();
            dm.AddDocument(new Document("Title A", "Sample A"));
            dm.AddDocument(new Document("Title B","Sample B"));
            dm.DisplayAllDocuments();
            if (dm.IsDocumentAvailable)
            {
                Document d = dm.GetDocument();
                Console.WriteLine(d.Content);
            }
        }
    } 


}
3.继承

泛型类型可以实现泛型接口,也可以派生自一个类。泛型类可以派生自泛型基类,要求是必须重复接口的泛型类型或者指定基类的类型。

例如:

public class Base<T>

{

}

public class Derived<T> :Base<string>

{

}

public class Derived<T> :Base<T>

{

}


4.静态成员

泛型类的静态成员只能在类的一个实例中共享。例如

public class StaticDemo<T>

{

public static int x;

}

使用时

StaticDemo<string>.x = 4;

StaticDemo<int>.x = 5;

Console.WriteLine(StaticDemo<string>.x);//4

### C# 泛型类的使用方法与示例详解 #### 什么是泛型类泛型类是一种允许在其定义中指定一个或多个类的占位符(通常用 `T` 表示),从而可以在实例化时提供具体的类。这种设计使得类可以适用于多种数据类,而无需为每种类单独编写代码[^3]。 #### 定义泛型类 以下是定义一个简单的泛型类的方式: ```csharp public class GenericClass<T> { private T value; public GenericClass(T initialValue) { this.value = initialValue; } public void SetValue(T newValue) { this.value = newValue; } public T GetValue() { return this.value; } } ``` 上述代码展示了如何创建一个名为 `GenericClass` 的泛型类。该类有一个私有字段 `value` 和两个公共方法用于设置和获取此字段的值[^1]。 #### 添加约束条件 为了增强灵活性并确保类安全,可以通过 **where** 关键字参数添加约束条件。例如,如果希望传入的对象实现某个特定接口,则可以这样写: ```csharp public class ConstrainedGenericClass<T> where T : IExample { public void ExecuteMethod(T obj) { obj.ExampleMethod(); } } ``` 在此例子中,只有实现了 `IExample` 接口的类才能作为 `ConstrainedGenericClass` 类中的参数传递给它[^2]。 #### 实际应用案例分析 假设我们需要存储不同类的学生信息(如姓名字符串或者年龄整数)。我们可以利用前面提到的知识构建如下解决方案: ```csharp // 学生实体基类 public abstract class StudentBase {} // 字符串学生派生类 public class StringStudent : StudentBase, IExample { public string Name { get; set; } public void ExampleMethod() { Console.WriteLine($"String student's name is {Name}"); } } // 整形学生派生类 public class IntStudent : StudentBase, IExample { public int Age { get; set; } public void ExampleMethod() { Console.WriteLine($"Int student's age is {Age}"); } } class Program { static void Main(string[] args) { var genericInstanceForStrings = new GenericClass<StringStudent>(new StringStudent { Name = "Alice" }); genericInstanceForStrings.CallExampleMethod(genericInstanceForStrings.GetValue()); var genericInstanceForInts = new GenericClass<IntStudent>(new IntStudent { Age = 20 }); genericInstanceForInts.CallExampleMethod(genericInstanceForInts.GetValue()); } } ``` 通过以上程序可以看到我们成功地将不同种类的数据封装进了同一个逻辑框架下操作。 #### 总结 C# 中的提供了强大的功能来提升代码质量,包括但不限于更高的性能、更好的维护性和更强的安全保障。合理运用这些特性可以帮助开发者写出更加优雅高效的软件产品。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值