Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.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
.NET中的包装器类型:结构还是类?_.net_Types_Wrapper - Fatal编程技术网

.NET中的包装器类型:结构还是类?

.NET中的包装器类型:结构还是类?,.net,types,wrapper,.net,Types,Wrapper,考虑以下场景: int Caller1<T>(T t) where T : IInterface {...} T Caller2<T>() where T : IInterface {...} class Wrappee // doesn't implement IInterface, but could ??? Wrapper : IInterface { private readonly Wrappee _wrappee; // methods call

考虑以下场景:

int Caller1<T>(T t) where T : IInterface {...}
T Caller2<T>() where T : IInterface {...}

class Wrappee // doesn't implement IInterface, but could

??? Wrapper : IInterface {
  private readonly Wrappee _wrappee;

  // methods call _wrappee's methods
}
在这种情况下,
Wrapper
应该是一个类,以避免装箱

对认识Haskell的人说:我正试图找到与
newtype
最接近的.NET类似物


更新:在第一种情况下,如果没有装箱,请参阅和。

我会说类,因为您封装的是行为,而不仅仅是数据。

是的,因为您将通过一个IInterface变量访问包装器,为了避免装箱,它应该是一个类


编辑:如果您通过类型为wrapper的变量访问wrapper,并访问wrapper方法,而不是i接口方法,那么结构就可以了。

通常您的类/结构将由您调用的方法存储或在内部传递(您没有显示调用方1和调用方2的操作),在这种情况下,它可能会被装箱。可能比你想象的要频繁。所以,除非你能证明一个结构会更有效率:不要麻烦,只要坚持使用一个类就行了

此外,除非结构表示类似于数据类型的内容,否则结构通常是不受欢迎的,因此选择一个类可能会阻止将来讨论不同性质的内容


但是,如果性能确实是一个问题,并且如果您可以保证实例仅作为带有泛型类型约束的参数传递,并且从不存储在接口类型的字段或集合中,那么.NET运行时当前的结构内联将更加有效,因为您的包装器结构大部分都将被优化。但是这是很多的ifs。

为什么你认为使用结构作为泛型类型参数会对装箱的需要产生影响?我不是通过
IInterface
变量访问它,而是一个受限于从
IInterface
派生的泛型参数。请参阅更新。也就是说,调用代码类似于:
Wrapper y=Caller2();返回呼叫者1(y)
int Caller(IInterface t) {...}