您的位置:首页 > 娱乐 > 明星 > c#10 语法特性

c#10 语法特性

2024/10/6 2:20:55 来源:https://blog.csdn.net/weixin_45924250/article/details/140016351  浏览:    关键词: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}";

```

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com