Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 约束与使用SafeHandle的抽象类_C#_Pinvoke_Safehandle - Fatal编程技术网

C# 约束与使用SafeHandle的抽象类

C# 约束与使用SafeHandle的抽象类,c#,pinvoke,safehandle,C#,Pinvoke,Safehandle,BCryptNative中有一个名为的方法。 其签名如下: internal static int GetInt32Property<T>(T algorithm, string property) where T : SafeHandle internal static int GetInt32Property(SafeHandle algorithm, string property) Microsoft使用函数指针/委托指向正确的本机函数。我的问题是,为什么Microsof

BCryptNative中有一个名为的方法。 其签名如下:

internal static int GetInt32Property<T>(T algorithm, string property) where T : SafeHandle
internal static int GetInt32Property(SafeHandle algorithm, string property)
Microsoft使用函数指针/委托指向正确的本机函数。我的问题是,为什么Microsoft不使用以下签名实现GetInt32Property方法:

internal static int GetInt32Property<T>(T algorithm, string property) where T : SafeHandle
internal static int GetInt32Property(SafeHandle algorithm, string property)
使用以下本机方法:

[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetProperty(SafeHandle hObject,
                                                   string pszProperty,
                                                   [MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
                                                   int cbOutput,
                                                   [In, Out] ref int pcbResult,
                                                   int flags);
这有什么坏处吗?(假设传递给GetInt32Property的SafeHandle始终为或)

我只是想知道为什么微软要实施如此复杂的程序

它是否必须与:

  • 安全透明代码
  • 类型安全?(这样您就不会使用这两种类型以外的任何其他类型)
  • 是否允许显式使用SafeHandle

根据定义,类必须被继承,并且是继承的,但是当给定一个抽象的SafeHandle类时,p/调用函数是否正确地处理它?它是否适当地增加和减少引用计数?

很难说微软为什么选择以这样或那样的方式实现某些东西,但我可以回答你的观点

  • 代码并不复杂。用法很清楚(类似于
    GetInt32Property(algorithm,str)
  • 它不会强制您发送您提到的类型之一,您仍然可以使用其他类调用它,只要它实现了
    SafeHandle
  • 使用的本地方法实际上是相同的。这有点奇怪,但我不是这个特定库的专家,所以这可能是有原因的
  • 像这样的泛型方法有一个隐藏的好处。
    typeof(T)==typeof(SafeBCryptHashHandle)
    类型检查不是在运行时完成的,而是在JIT时间完成的。这意味着该方法的执行速度应该比常规运行时检查(如
    algorith is SafeBCrypthHashHandle
    稍快一些

SafeHandle
类是一个抽象类。这意味着您不能创建它的实例,但可以继承它。本机函数只获取封送数据,它们不会获取对象的真实引用。不要担心引用计数。

啊,太好了!谢谢您,JIT时间段非常有趣,尽管我仍然没有理解他们为什么为了这么小的利益而增加这么多麻烦。无论如何,谢谢你的回答:)