指定参数构造器

using System;
class A
{
    
public A()
    
{
        Console.WriteLine(
"我是类A的无参构造器");
    }

    
public A(int i)
    
{
        Console.WriteLine(
"我是类A带一个整型参数的构造器"+i.ToString());
    }

}

class B:A
{
    
public B()
    
{
        Console.WriteLine(
"我是类B的无参构造器");
    }

    
public B(int i):base(i)//指定参数构造器
    {
        Console.WriteLine(
"我是类B带一个整型参数的构造器");
    }

}

class Test
{
    
static void Main()
    
{
        B b 
= new B(8);
    }

}
 
### TypeScript 构造器参数装饰器的用法 在 TypeScript 中,构造函数参数上的装饰器用于修改类的行为或向其添加元数据。当应用于构造函数的参数时,装饰器会在实例化对象之前执行。 #### 装饰器基础概念 装饰器本质上是一个函数,在定义阶段被调用并传入描述目标实体的信息作为参数。对于构造函数参数来说,它接收三个固定参数:目标类原型、属性名以及该参数的位置索引[^1]。 ```typescript function paramDecorator( target: any, propertyKey: string | symbol, parameterIndex: number ) { console.log(`Parameter at index ${parameterIndex} of method "${String(propertyKey)}"`); } ``` #### 实际案例展示 下面的例子展示了如何利用装饰器来记录某个特定服务注入到组件中的位置: ```typescript // 定义一个简单的日志装饰器 function logParam(target: Object, methodName: string | symbol, paramIdx: number): void { let originalMethod = target[methodName]; // 修改方法行为以便打印参数信息 target[methodName] = function (...args: any[]) { const argValue = args[paramIdx]; console.log(`${methodName.toString()} called with argument[${paramIdx}] value=${argValue}`); return originalMethod.apply(this, arguments); }; } class Service {} class Component { constructor(@logParam private service: Service) {} } new Component(new Service()); ``` 上述代码片段中,`@logParam` 将会拦截 `Component` 类构造过程中传递给它的第一个参数,并输出相应的调试信息至控制台。 #### 结合接口实现更复杂的功能 除了基本的日志功能外,还可以通过组合其他特性(比如接口),创建更加复杂的逻辑处理流程。例如,验证输入的数据是否满足指定条件等操作可以在初始化期间完成[^2]。 ```typescript interface Validatable { validate(value: unknown): boolean; } function validation(paramValidator: (value: unknown) => boolean) { return function ( target: object, key: string | symbol, descriptor: PropertyDescriptor | number ) { if (typeof descriptor === 'number') { Reflect.defineMetadata(key.toString(), paramValidator, target.constructor, descriptor); } }; } class EmailService implements Validatable { validate(email: string): boolean { return /\S+@\S+\.\S+/.test(email); // 简单邮箱正则表达式匹配 } } class Account { @validation((email) => new EmailService().validate(email)) set email(val: string) { this._email = val; } get email() { return this._email; } private _email!: string; constructor(@validation((email) => new EmailService().validate(email)) public signupEmail: string) {} } const accountInstance = new Account('example@example.com'); console.log(accountInstance.email); // 输出 "example@example.com" ``` 在这个例子里面,不仅实现了对构造函数参数的有效性检验,同时也扩展到了 setter 方法上,确保每次设置 `_email` 属性的时候都会触发有效性校验过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值