前言
我之前发布过一些篇章,是专门关于代码优化的,距离我上一次[如何优雅的写C#]已经过去半年时间了,最近我又研究出了一些新东西。
相关文章
如何让代码优雅
我对于优雅有几个简单的定义
- 做的多,写的少
- 尽可能的减少入参,只需要关键参数
- 低耦合
- 低耦合就是可改动行强,比如一个1米的积木改成10个0.1米的积木,这个就是降低耦合。
- 阅读性,可维护性强
- 尤其是可阅读性,逻辑性要符合人类正常思考问题,解决问题的思维。
知识点补充
这些其实都是很简单的知识点,我这里重新讲解一下好了
enum枚举类型
枚举类型相当于静态字符串,这里不多讲解,不过枚举类型可以和扩展方法搭配使用。
public class MyTest
{
public enum MyTestKey
{
Key1, Key2, Key3, Key4, Key5, Key6
}
}
/// <summary>
/// 扩展方法必须写在静态类里面
/// </summary>
public static class MyTestExtension
{
/// <summary>
/// this指向枚举类型
/// </summary>
/// <param name="test"></param>
public static void PrintValue(this MyTestKey test)
{
Console.WriteLine(test.ToString());
}
}
使用
static void Main(string[] args)
{
MyTestKey.Key1.PrintValue();
Console.WriteLine("运行完成!");
Console.ReadKey();
}
?null判定
List<string> list = null;
//空值判断
Console.WriteLine(list?.Count);
//三元表达式
Console.WriteLine(list == null?"":list.Count );
//传统if/else
if(list == null)
{
Console.WriteLine();
}
else
{
Console.WriteLine($"{list.Count}");
}