0Pricing
C# Academy · 课时

unmanaged、notnull、new()(C# 6 模拟)

C# 6 支持 class/struct/new() 约束;通过保护性检查、API 形态和约定来模拟较新的 notnull/unmanaged。

unmanaged、notnull、new()(C# 6 模拟) 是 CoddyKit 上的免费 C# Academy 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

约束全景

目标:有效使用 C# 6 的泛型约束。

  • 类与结构体的区别
  • 使用无参数构造约束实现无需激活器的创建
  • 通过保护条件和 API 设计模拟非空约束/非托管意图

类与结构体

类约束将 T 限制为引用类型;结构体约束将 T 限制为值类型。误用会在编译时失败。

using System;

// Works only for reference types
public static class RefBox
{
  public static string Show<T>(T value) where T : class
  {
    return value == null ? "null ref" : "ref: " + value.ToString();
  }
}

// Works only for value types
public static class ValBox
{
  public static string Show<T>(T value) where T : struct
  {
    return "value: " + value.ToString();
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    string s = "hello";
    int n = 42;

    Console.WriteLine(RefBox.Show<string>(s)); // OK
    Console.WriteLine(ValBox.Show<int>(n));    // OK

    // Console.WriteLine(RefBox.Show<int>(n)); // compile-time error (int is struct)
    // Console.WriteLine(ValBox.Show<string>(s)); // compile-time error (string is class)
  }
}

无参数构造约束的实际用法

无参数构造约束保证类型参数具有公共 parameterless 构造函数,因此泛型代码可以直接创建 T。

using System;

// Requires public parameterless ctor on T
public static class Factory
{
  public static T Create<T>() where T : new()
  {
    return new T(); // safe in C# 6 with new()
  }
}

public sealed class Sample
{
  public string Name { get; set; }
  public Sample() { Name = "default"; }
}

public class Program
{
  public static void Main(string[] args)
  {
    Sample x = Factory.Create<Sample>();
    Console.WriteLine("Created: " + x.Name);
  }
}

模拟非空约束

C# 6 中没有非空约束。可以通过将 T 约束为引用类型,再在 API 内部显式添加空值保护来近似实现。

using System;

// C# 6 has no notnull constraint. Use where T : class and guard at runtime.
public static class NotNullApi
{
  public static int LengthOf<T>(T x) where T : class
  {
    if (x == null) throw new ArgumentNullException("x");
    return x.ToString().Length; // placeholder usage
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Console.WriteLine(NotNullApi.LengthOf<string>("hi")); // 2
    try
    {
      Console.WriteLine(NotNullApi.LengthOf<string>(null)); // throws
    }
    catch (Exception ex)
    {
      Console.WriteLine("Guard fired: " + ex.GetType().Name);
    }
  }
}

模拟非托管意图

C# 6 中没有非托管约束。可以使用结构体和接口(例如可比较接口),以针对类似数值的值类型。

using System;

// No unmanaged constraint in C# 6.
// Use struct for value types and restrict API usage (document numeric-only intent).
public static class NumericOps
{
  public static T Max<T>(T a, T b) where T : struct, IComparable
  {
    // Works for numeric primitives because they implement IComparable
    return (a.CompareTo(b) >= 0) ? a : b;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Console.WriteLine(NumericOps.Max<int>(3, 9));     // 9
    Console.WriteLine(NumericOps.Max<double>(2.5, 2)); // 2.5
  }
}

实用提示

提示:

  • 尽早选择类/结构体来限制 T。
  • 如果需要创建 T,请使用无参数构造约束。
  • 使用运行时保护条件模拟非空约束。
  • 通过结构体加文档化用法(通常是数值基元类型)模拟非托管意图。

构造函数约束

快速检查:C# 6 中,哪个约束要求类型参数具有公共 parameterless 构造函数?

回顾

回顾:在 C# 6 中使用类/结构体/无参数构造约束。通过空值检查模拟非空约束,通过结构体加接口边界表达非托管意图。

常见问题解答

「unmanaged、notnull、new()(C# 6 模拟)」课时是免费的吗?

是的 — 「unmanaged、notnull、new()(C# 6 模拟)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「unmanaged、notnull、new()(C# 6 模拟)」这节课中我会学到什么?

C# 6 支持 class/struct/new() 约束;通过保护性检查、API 形态和约定来模拟较新的 notnull/unmanaged。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。

「unmanaged、notnull、new()(C# 6 模拟)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. unmanaged、notnull、new()(C# 6 模拟)
  2. 泛型数学(概览)与泛型特性(适用时)
  3. 可复用的泛型工具
← 返回 C# Academy