c#10 语法特性


theme: smartblue

一、 属性拓展

创建实体类

``` public class Student { public int Id { get; set; } = 24;

public string Name { get; set; } = "xyy";


    public Address address { get; set; }
}

public class Address
{
    public string position { get; set; }
}

``` 当一个类为 object 且要根据某个属性进行筛选时

``` object obj = new Student { address = new Address { position = "anhui" } };

if(obj is Student { address :{position:"anhui" } }) { Console.WriteLine("anhui"); }

```

二、 lambda 表达式改进

2.1 调用特性内的方法

自定义特性 public class TestAttribute:Attribute { public void Show() { Console.WriteLine($"{this.GetType().FullName} was build."); } } 调用特性内的方法

var f1 = [TestAttribute] () =>{}; MethodInfo methodInfo = f1.GetMethodInfo(); TestAttribute testAttribute = methodInfo.GetCustomAttribute<TestAttribute>(); testAttribute.Show();

2.2 调用静态修饰的特性内方法

var f1 = [TestAttribute] static (int x) =>x; MethodInfo methodInfo = f1.GetMethodInfo(); TestAttribute testAttribute = methodInfo.GetCustomAttribute<TestAttribute>(); testAttribute.Show();

2.3 调用有返回值的特性内方法

var f1 = [DoesNotReturn:TestAttribute] (int x) =>x; ICustomAttributeProvider returnTypeCustomAttributes = f1.GetMethodInfo().ReturnTypeCustomAttributes; object[] objects = returnTypeCustomAttributes.GetCustomAttributes(typeof(TestAttribute),true); foreach(TestAttribute attrbute in objects) { attrbute.Show(); }

三、 常数内插字符串

``` const string firstName = "f"; const string lastName = "l"; const string name = $"{firstName} {lastName}";

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值