C# params使用

在 C# 中,params 关键字用于定义**可变参数列表(variable-length argument list)**的方法参数。它允许调用者传入 0 个或多个指定类型的参数,而无需显式创建数组。

你提到的 params Type[] interfaceTypes 是一个典型的使用场景:方法接收任意数量的 Type 对象(通常表示接口类型),用于反射、依赖注入、插件系统等。


一、params 基本语法

csharp 复制代码
public void MyMethod(params int[] numbers)
{
    foreach (int n in numbers)
        Console.WriteLine(n);
}

// 调用方式:
MyMethod();           // numbers = new int[0]
MyMethod(1);          // numbers = new int[] { 1 }
MyMethod(1, 2, 3);    // numbers = new int[] { 1, 2, 3 }

规则

  • params 必须是方法的最后一个参数
  • 一个方法只能有一个 params 参数。
  • 调用时可以直接传多个值,也可以传一个数组。

二、params Type[] interfaceTypes 的典型用法

场景:检查某个类型是否实现了指定的一组接口

csharp 复制代码
public static bool ImplementsAllInterfaces(Type targetType, params Type[] interfaceTypes)
{
    if (interfaceTypes == null || interfaceTypes.Length == 0)
        return true; // 没有要求接口,视为满足

    var implementedInterfaces = targetType.GetInterfaces();
    foreach (var iface in interfaceTypes)
    {
        if (!implementedInterfaces.Contains(iface))
            return false;
    }
    return true;
}
调用示例:
csharp 复制代码
// 定义接口和类
public interface IRunnable { }
public interface IFlyable { }
public class Bird : IRunnable, IFlyable { }

// 使用
Type birdType = typeof(Bird);

// 方式1:直接传多个 Type
bool result1 = ImplementsAllInterfaces(birdType, typeof(IRunnable), typeof(IFlyable));

// 方式2:传数组(等效)
Type[] required = { typeof(IRunnable), typeof(IFlyable) };
bool result2 = ImplementsAllInterfaces(birdType, required);

// 方式3:不传(空参数)
bool result3 = ImplementsAllInterfaces(birdType); // 返回 true

三、其他常见用途

1. 动态创建实现多个接口的代理(如 Castle DynamicProxy)

csharp 复制代码
proxyGenerator.CreateClassProxy(
    typeof(MyClass),
    new[] { typeof(IInterceptor) },
    params Type[] additionalInterfacesToProxy // ← 这里常用 params
);

2. 注册服务时指定多个接口

csharp 复制代码
public void RegisterService(Type implementation, params Type[] serviceTypes)
{
    foreach (var service in serviceTypes)
    {
        container.Register(service, implementation);
    }
}

// 调用
RegisterService(typeof(Logger), typeof(ILogger), typeof(IDisposable));

3. 断言对象是否实现某些接口(单元测试)

csharp 复制代码
public void AssertImplements(object obj, params Type[] expectedInterfaces)
{
    Type actualType = obj.GetType();
    foreach (var iface in expectedInterfaces)
    {
        Assert.IsTrue(actualType.GetInterfaces().Contains(iface));
    }
}

四、注意事项

❗ 1. params 参数可以为 null

csharp 复制代码
MyMethod(null); // 此时 params 数组为 null!

因此在方法内部应做空值检查:

csharp 复制代码
public void Foo(params string[] args)
{
    if (args == null) 
    {
        // 处理 null 情况
    }
}

❗ 2. 类型安全

params Type[] 要求传入的每个参数必须是 Type 类型(通常是 typeof(接口)),不能传接口实例。

✅ 正确:

csharp 复制代码
Check(typeof(ISerializable), typeof(IDisposable));

❌ 错误:

csharp 复制代码
ISerializable obj = ...;
Check(obj); // 编译错误!obj 不是 Type 类型

❗ 3. 性能

每次调用会隐式创建数组(除非传入已有数组),高频调用需注意分配开销。


五、完整示例:通用接口验证工具

csharp 复制代码
using System;
using System.Linq;

public static class InterfaceChecker
{
    public static bool HasAllInterfaces(Type type, params Type[] requiredInterfaces)
    {
        if (requiredInterfaces == null || requiredInterfaces.Length == 0)
            return true;

        var implemented = type.GetInterfaces();
        return requiredInterfaces.All(implemented.Contains);
    }
}

// 测试
interface IA { }
interface IB { }
class MyClass : IA, IB { }

class Program
{
    static void Main()
    {
        bool ok = InterfaceChecker.HasAllInterfaces(
            typeof(MyClass),
            typeof(IA),
            typeof(IB)
        );
        Console.WriteLine(ok); // True
    }
}

总结

  • params Type[] interfaceTypes 是一种灵活接收多个接口类型的写法。
  • 常用于反射、依赖注入、AOP、插件架构等需要动态处理类型的场景。
  • 调用简洁,但需注意 null、性能和类型安全。
  • 它让 API 更友好:用户无需手动构造数组。
相关推荐
Z9fish4 分钟前
sse哈工大C语言编程练习20
c语言·开发语言·算法
萧鼎28 分钟前
Python 包管理的“超音速”革命:全面上手 uv 工具链
开发语言·python·uv
Anastasiozzzz1 小时前
Java Lambda 揭秘:从匿名内部类到底层原理的深度解析
java·开发语言
缺点内向1 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
刘琦沛在进步1 小时前
【C / C++】引用和函数重载的介绍
c语言·开发语言·c++
机器视觉的发动机1 小时前
AI算力中心的能耗挑战与未来破局之路
开发语言·人工智能·自动化·视觉检测·机器视觉
HyperAI超神经1 小时前
在线教程|DeepSeek-OCR 2公式/表格解析同步改善,以低视觉token成本实现近4%的性能跃迁
开发语言·人工智能·深度学习·神经网络·机器学习·ocr·创业创新
R_.L1 小时前
【QT】常用控件(按钮类控件、显示类控件、输入类控件、多元素控件、容器类控件、布局管理器)
开发语言·qt
喵叔哟2 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
Zach_yuan2 小时前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络