English 中文(简体)
我能否发现我是否作为参数获得了新的物体?
原标题:Can I detect whether I ve been given a new object as a parameter?

Short Version

那些没有时间阅读我对这个问题的推理的人:

www.un.org/Depts/DGACM/index_spanish.htm 是否有办法执行“仅限新物体”或“仅限现有物体”的方法的政策?

Long Version

有许多方法将物体作为参数,而这种方法是否具有“全部”目标,则无关紧要。 例如:

var people = new List<Person>();

Person bob = new Person("Bob");

people.Add(bob);
people.Add(new Person("Larry"));

此处为<代码>List<Person> 添加的方法采用了“现有”<代码>Person(Bob)和“新”<代码>Person(Larry),该清单载有这两个项目。 可在bobpeople[0]上查阅。 可在此后作为<条码>人=1查询,如有必要,可上网查阅<条码>。

OK, 罚款。 但是,有时一种真正意义上的方法(shouldn t)会被采纳为新目标。 例如,请<代码>Array。 Sort<T>。 下面的字面意思是:

Array.Sort<int>(new int[] {5, 6, 3, 7, 2, 1});

上述所有法典都采用新的阵列,然后忘记(因为其参考数字在<条码>后达到零;int>的退出,因此,如果I m不错,则将收集垃圾。 http://code>Array.Sort<T>>expects a “存在于”下阵列作为其论点。

可以想象的是,还有其他一些方法可以expect“new” Object(但我一般认为,期望这种期望会是一种设计错误)。 一个不完美的例子就是:

DataTable firstTable = myDataSet.Tables["FirstTable"];
DataTable secondTable = myDataSet.Tables["SecondTable"];

firstTable.Rows.Add(secondTable.Rows[0]);

正如我说过的那样,自以来,这只是一个伟大的例子。 ,该编码已经属于<代码>的可测量<>。 因此,上述法典的最后一行赢得了打工,需要:

firstTable.ImportRow(secondTable.Rows[0]);

不管怎么说,这还是我的问题的很多确定,即: 是执行“仅限新物体”或“仅限现有物体”方法政策的任何方法,无论是在其定义中,还是在其方法本身中(或许是由某些习俗认定我不知道的),还是在方法上(也许通过思考,即使有的话,我可能回避这一政策)?

如果不是的话,对于如何做到这一点,任何有意义的想法都会受到欢迎。 例如,如果能以某种方式获得某个特定物体的GC参考,那么你就可以在一种方法开始时告诉大家,你是否收到新物体(假设你重新处理参考类型,当然这是这个问题唯一相关的假设)。


www.un.org/Depts/DGACM/index_spanish.htm

较长的版本更长。

一切权利,即我有某种方法,希望能选择性地接受“<>TextWriter,以取得进步或做什么:

static void TryDoSomething(TextWriter output) {
    // do something...
    if (output != null)
        output.WriteLine("Did something...");
    
    // do something else...
    if (output != null)
        output.WriteLine("Did something else...");
    
    // etc. etc.
    
    if (output != null)
        // do I call output.Close() or not?
}

static void TryDoSomething() {
    TryDoSomething(null);
}

现在,请允许我考虑两种不同的方法:

string path = GetFilePath();
using (StreamWriter writer = new StreamWriter(path)) {
    TryDoSomething(writer);

    // do more things with writer
}

OR:

TryDoSomething(new StreamWriter(path));

Hmm. ......这似乎会造成问题,难道没有问题? I ve Construction a StreamWriter, which implementings IDisposable, but TryDoSomething 不知道它是否完全可以查阅其<代码>output论点。 因此,该物体要么过早处置(在第一个案例中),要么完全处置(在第二种情况下)。

我不想说,这必然是一个巨大的设计。 也许Stodola是正确的,从一开始,这只是一个坏的想法。 不管怎么说,我问这个问题,主要是因为我很奇怪,如果这样一件事情是possible。 答案是:不是真的。

最佳回答

基本上没有。

:

var x = new ...;
Foo(x);

以及

Foo(new ...);

以及 indeed sometimes you might convert between the two for debugging purposes.

Note that in the DataRow/DataTable example, there s an alternative approach though - that DataRow can know its parent as part of its state. That s not the same thing as being "new" or not - you could have a "detach" operation for example. Defining conditions in terms of the genuine hard-以及-fast state of the object makes a lot more sense than woolly terms such as "new".

问题回答

www.un.org/Depts/DGACM/index_spanish.htm 是的。

Sort of.

如果你把其参数作为<条码>ref参数,那么你就必须有作为你的论据的现有变量。 你可以做这样的事情:

DoSomething(ref new Customer());

如果你这样做,你就错了,“撤回或排除论点必须是可转让的变量”。

当然,使用参考书具有其他影响。 但是,如果是you re 书写这种方法的人不需要担心。 只要你不把重负参数重新调配到该方法中,那么无论你是否使用,它就没有取得任何变化。

我不说它有好风格,必然。 除非你真的确实需要而且没有其他方式来做你重新做的事情,否则你就不得使用。 但是,如果使用否决权,你想要做些什么。

页: 1 如果你有理由这样做,那么你的法典有不适当的结构。

简短回答:无

在绝大多数情况下,我通常认为,你上文列举的问题并不真正如此。 如果你能够超负荷使用某种方法,以便你能够接受其他东西作为参数,而不是你担心分享的物体。

// For example create a method that allows you to do this:
people.Add("Larry");

// Instead of this:
people.Add(new Person("Larry"));

// The new method might look a little like this:
public void Add(string name)
{
    Person person = new Person(name);
    this.add(person); // This method could be private if neccessary
}

我可以考虑这样做的办法,但我肯定不会建议这样做。 只是为了论点。

它意味着某一物体是“新”物体? 这意味着只剩下一字。 “现有”物体将不止一个提及。

考虑到这一点,研究以下法典:

    class Program
    {
        static void Main(string[] args)
        {
            object o = new object();

            Console.WriteLine(IsExistingObject(o));
            Console.WriteLine(IsExistingObject(new object()));

            o.ToString();  // Just something to simulate further usage of o.  If we didn t do this, in a release build, o would be collected by the GC.Collect call in IsExistingObject. (not in a Debug build)
        }

        public static bool IsExistingObject(object o)
        {
            var oRef = new WeakReference(o);

#if DEBUG 
            o = null; // In Debug, we need to set o to null.  This is not necessary in a release build.
#endif
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return oRef.IsAlive;
        }
    }

This prints True on the first line, False on the second. But again, please do not use this in your code.

让我把你的问题改成一个较短的问题。

在我看来,用什么方法把物体当作理由来知道该物体是否在我的方法之外使用?

答案是:No.

请允许我就此发表看法: 不应当有任何这样的机制。

这将使整个地点采用的方法复杂化。

如果采用某种方法,我可以说明所标的1米是否真的被使用,那么,这种方法就会向我发出信号,作为这种方法的制定者,将这一点考虑在内。

基本上,你们都看到这种类型的法典在任何地方都存在(因为有线可查/支持):

if (ReferenceCount(obj) == 1) return; // only reference is the one we have

我认为: 如果有: 电话 贵方的手法不会将物体用于任何用途,在修改物体之外没有副作用,因此,不应先从该代码开始。

它喜欢这样的法典:

1 + 2;

该法典做了些什么? 但这取决于C/C++的汇编者,其might<>/em>汇编成对1+2进行评价的内容。 你们是否利用它做什么? 无 那么,这部法典是贵国来源法典的一部分?

当然,你可以认为,该守则实际上是a+b;,目的是确保对<代码>a+b的评价。 有时不会放弃一个例外,而这种情形却非常少见,因为这样一例特别情况只会掩盖真正的问题,而仅仅将问题分配给一个临时变量,便可以简单地加以确定。

无论如何,对于任何方案拟定语言和(或)操作时间及(或)环境的任何特征,如果存在一个特征的话,说明为何没有这种特征的原因如下:

  • It wasn t designed properly
  • It wasn t specified properly
  • It wasn t implemented properly
  • It wasn t tested properly
  • It wasn t documented properly
  • It wasn t prioritized above competing features

所有这些都需要在申请Y的第十版,无论是C# 4.0,还是MS Works 7.0中出现一个特征。

Nope,没有知情的途径。

全部通过都是标的。 无论是从表面上来看还是从阵列中产生,有关方法都无法知道这些参数是如何在瞬间和(或)什么地方通过的。

了解在要求功能/方法之前是否设定了目标(或一种方法)的一种办法是,该物体拥有从系统功能中抽出的时间段后即开始使用的财产;这样,看该财产,就有可能解决这个问题。

坦率地说,我不会使用这种方法,因为这样做是因为

  • I don t see any reason why the code should now if the passed parameter is an object right created, or if it has been created in a different moment.
  • The method I suggest depends from a system function that in some systems could not be present, or that could be less reliable.
  • With the modern CPUs, which are a way faster than the CPUs used 10 years ago, there could be the problem to use the right value for the threshold value to decide when an object has been freshly created, or not.

The other solution would be to use an object property that is set to a a value from the object creator, and that is set to a different value from all the methods of the object.
In this case the problem would be to forget to add the code to change that property in each method.

我要再次请我“真的需要做吗?

如果你只想用一种方法消费某个物体之一,那么作为可能的局部解决办法,你可能会看一个单一州。 这样,如果有关方法已经存在,就不能再造成另一种情况。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...