加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何获取一个ID,让我能够区分一个类的不同实例?

发布时间:2020-12-15 07:39:10 所属栏目:百科 来源:网络整理
导读:想象一下,我有一个类,有两个实例: MyClass a = new MyClass();MyClass b = new MyClass(); MyClass有一个方法PrintUniqueInstanceID: void PrintUniqueInstanceID(){ Console.Write("Unique ID for the *instance* of this class: {0}",[what goes here???
想象一下,我有一个类,有两个实例:
MyClass a = new MyClass();
MyClass b = new MyClass();

MyClass有一个方法PrintUniqueInstanceID:

void PrintUniqueInstanceID()
{
  Console.Write("Unique ID for the *instance* of this class: {0}",[what goes here???]
  );
}

理想情况下,输出结果如下:

Unique ID for the *instance* of this class: 23439434        // from a.PrintUniqueInstanceID
Unique ID for the *instance* of this class: 89654           // from b.PrintUniqueInstanceID

那么 – 我将在上面的“[what goes here ???]”中插入什么,为类的每一个独特的实例打印一个唯一的编号?

思路

>也许将“this”转换为int指针,并使用它?
>使用GCHandle不知何故?
>在方法中访问“this”的属性,以唯一标识它?

(可选)专家背景资料

我需要这个的原因是我正在使用AOP和PostSharp来自动检测线程问题.我需要在字典中查找类的每个唯一实例,以便验证多个线程是否不访问类的同一唯一实例(如果每个类实例有一个线程,则确定它).

更新

正如其他人所指出的那样,我应该提到,我不能接触30,000线项目中的任何现有课程. PrintUniqueInstanceID上面是添加到顶级类的一个方面(参见PostSharp),由整个项目中的每个类继承,并在整个项目的每个方法条目上执行.

一旦我验证一切都是线程安全的,我将删除该方面以恢复性能.

解决方法

将一个Guid属性添加到你的类中,然后在类的构造函数中将它赋给NewGuid().
public class MyClass
{
    public Guid InstanceID {get; private set;}
    // Other properties,etc.

    public MyClass()
    {
        this.InstanceID = Guid.NewGuid();
    }

    void PrintUniqueInstanceID() 
    {   
        Console.Write("Unique ID for the *instance* of this class: {0}",this.InstanceID); 
    } 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读