.net的一些知识点6

发布于:2025-02-12 ⋅ 阅读:(78) ⋅ 点赞:(0)

1.写个Lazy<T>的单例模式

 public class SingleInstance
 {

     private static readonly Lazy<SingleInstance> instance = new Lazy<SingleInstance>(() => new SingleInstance());

     private SingleInstance()
     {

     }
     

     public static SingleInstance Instace => instance.Value;

     public void Test()
     {
         Console.WriteLine("Test");
     }

 }

2.单例模式会用在什么地方

数据库连接

日志

线程池管理

3.数据库连接释放如何进行

SqlConnection实例化的对象con

con.Close();

con.Dispose();

3.发布-订阅模式

发布的类定义一个delegate,定义一个event,两者访问权限与返回类型必须一致

发布的类实例化后

调用订阅者的方法,订阅者的方法的访问权限以及返回类型必须和代理一致

  PublishDemo publishDemo = new PublishDemo();
  publishDemo.MyEvent += new SubscriberDemo().Write;
  publishDemo.Test("aaa");

4.发布类方法调用的注意点:

internal class PublishDemo
{

    public delegate void MyDelegate(string str);

    public event MyDelegate MyEvent;

    public void Test(string s)
    {
        //MyEvent(s);如果没有订阅者,会报错
        MyEvent?.Invoke(s);
    }


}

5.如何读取一个类的属性

a.类实例化一个对象

b.对象.GetType().GetProperties();//Properties,因为属性几乎不会只有一个

c.得到当前值,然后遍历一下,即可获取属性名称

   MyEntity myEntity = new MyEntity();
   myEntity.Id = 1;
   myEntity.Name = "ddfffsdfsdfs";
   PropertyInfo[] items = myEntity.GetType().GetProperties();
   foreach (var item in items)
   {
       
       Console.WriteLine(item.Name + ":" + item.PropertyType + ":"+ item.GetValue(myEntity));
       //item.GetValue(myEntity);用于取属性值
   }

6.定义一个结构体

//和类很像

struct Book{

public string Name;

}

struct,class,枚举,接口不能再main中定义

7.如何防止sql注入

a.sql参数化

b.用存储过程

c.不用同态sql

d.使用orm框架,比如ef框架

e.前端要有验证

f.数据库用户权限要慎重

8.使用存储过程的有点有哪些

a.防止sql注入

b.执行速度快

c.减少流量

9.如何交换俩个变量的值

a.用临时变量盛一下

b.用元组

c.用计算交换

10.说一个可以查看.net运行环境的命令

dotnet --info