是否有内置方法来识别类的实例?
我正在使用我的一个 C#.NET 项目进行一些诊断日志记录,我希望能够记录代表类的特定实例的标识符。我知道我可以使用静态变量来做到这一点,每次创建类实例时该变量都会递增,但我只是想知道 .NET 框架中是否有任何内置方法可以做到这一点。也许使用反射什么的。
I am doing some diagnostic logging with one of my C#.NET projects and I would like to be able to log an identifier that represents a specific instance of a class. I know I could do this with a static variable that just gets incremented every time a class instance is created but I am just wondering if there is any built-in way in the .NET framework to do this. Maybe using reflection or something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以向您的类添加一个
Guid
属性,并在构造函数中对其进行初始化(保证每个实例都是唯一的)。You could add a
Guid
property to your class an initialize it in the constructor (guaranteed unique for each instance).只是添加到 Henk 在他的回答中谈到了
GetHashCode
,并减轻了他对该答案收到的一些负面评论:有一种方法可以在
GetHashCode
上调用GetHashCode
任何独立于该对象值的对象,无论其类型是否已覆盖GetHashCode
。看一下
System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode
。
当然,这个值不能保证是唯一的。两者都不是
Guid
(尽管如果不是唯一的,则涉及的可能性是非常微小的)。我想说你对静态计数器变量的直觉是正确的。不过,我应该提到,在每个对象的构造函数中使用 ++ 运算符简单地增加它并不是线程安全的。如果可能的话,您可以从多个线程实例化一个类的实例,您将需要使用
Interlocked.Increment
相反。Just to add to what Henk said in his answer about
GetHashCode
, and to mitigate some of the negative comments he received on that answer:There is a way to call
GetHashCode
on any object that is independent of that object's value, regardless of whether or not its type has overriddenGetHashCode
.Take a look at
System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode
.This value is not guaranteed to be unique, of course. Neither is a
Guid
(though for that not to be unique would involve odds that are legitimately microscopic).I'd say your gut was right about the static counter variable. I should mention, though, that simply incrementing it using the
++
operator in each object's constructor is not thread-safe. If it's possible you could be instantiating instances of a class from multiple threads you would want to useInterlocked.Increment
instead.也许
Object.ReferenceEquals
可以解决您的问题。至少它可以告诉你一个对象是否与其他对象相同。您不能使用静态变量,因为它在每个实例中都是相同的。它只会有创建的对象的计数。
您可以使用 Jon B 的解决方案,或者如果您想要数字标识符,请使用静态计数器并将 id 分配给字段。
Maybe
Object.ReferenceEquals
solves your problem. At least it can tell you if an object is the same as some other.You can not use a static variable because it will be the same in each instance. It will just have the count of the objects created.
You have the possibility to use Jon B's solution or if you want numeric identifiers use a static counter and assign an id to a field.