如何In和Out属性在.NET中的工作? [英] How do the In and Out attributes work in .NET?

查看:188
本文介绍了如何In和Out属性在.NET中的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图序列化跨越的AppDomain 边界的数组,使用以下code:

I have been trying to serialize an array across an AppDomain boundary, using the following code:

public int Read(byte[] buffer, int offset, int count)
{
    return base.Read(buffer, offset, count);
}

作为一个猜测,在别处注意到的属性后,标志着我的方法与参数[IN] [OUT] 属性,这似乎引起的参数表现得好像他们是按引用传递。

As a guess, after noticing the attributes elsewhere, I marked the method's parameters with [In] and [Out] attributes, which seemed to cause the parameters to behave as if they were passed by reference.

例如:

public int Read([In, Out] byte[] buffer, int offset, int count)
{
    return base.Read(buffer, offset, count);
}

在我添加的属性,在缓存变量是从方法跨越的AppDomain 边界。

Before I added the attributes, the contents of the buffer variable were lost after returning from the method across an AppDomain boundary.

类( SslStream )从 MarshalByRefObject的继承,但没有打上了序列化属性。这是为了传递参数按值的唯一途径?难道这些属性被莫名其妙的.NET识别的类被序列化时?并做他们真正导致参数按引用传递,或者是刚才复制的内容?

The class (SslStream) was inheriting from MarshalByRefObject but not marked with the Serializable attribute. Is this the only way to make a parameter pass-by-value? Are these attributes being recognised somehow by .NET when the class is being serialised? And do they truly cause the parameter to be passed by reference, or are the contents just copied?

推荐答案

这是.NET远程的显着不良记录功能。它没有任何与你的类是[Serializable接口]或派生自MarshalByRefObject。这里的问题是如何的参数的跨应用程序域边界封送。调用本身是由远程引擎盖下进行。数组做的的自动获取封呼叫后回来,显然是一个性能优化。只需要[OUT]属性,[在]是不言而喻的。我找不到这个MSDN中的任何相关文件,只需从博客帖子有人说碰到了同样的问题(向下滚动到远程处理中使用OutAttribute)。

This is a remarkably poorly documented feature of .NET Remoting. It doesn't have anything to do with whether your class is [Serializable] or derived from MarshalByRefObject. At issue here is how the argument is marshaled across the AppDomain boundary. The call itself is made under the hood by Remoting. Arrays do not automatically get marshaled back after the call, clearly a performance optimization. Only the [Out] attribute is required, [In] is implied. I could not find any relevant documentation about this in MSDN, just a blog post from somebody that ran into the same issue (scroll down to "Using OutAttribute in Remoting").

有些code一起玩:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        var ad = AppDomain.CreateDomain("second");
        var t = (Test)ad.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName);
        var b = new byte[] { 1 };
        t.Read(b);
        System.Diagnostics.Debug.Assert(b[0] == 2);
    }
}

class Test : MarshalByRefObject {
    public void Read([Out]byte[] arg) {
        arg[0] *= 2;
    }
}

这篇关于如何In和Out属性在.NET中的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆