收集类实例的集合 [英] Gather a collection of Class instances

查看:60
本文介绍了收集类实例的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,

我已经做了一些搜索,但我要么找不到答案,要么就是不理解它。



我的应用程序中使用了特定类的几个实例。所有实例都具有需要保持唯一的字符串属性[标题]。为此,我决定在类中添加一个数字

,并在标题设置为与此

类的另一个实例相同的值时递增它。

为此,我需要计算包含相同值的类的每个实例[title_]



请检查帮助下的休息代码





最终我计划为用户选择列出所有这些实例。



我知道有一种方法可以在System.windows.application.Openforms下的应用程序中收集打开的表单然后使用gettype()检查表单类型但是我不确定

如果可以对类实例执行相同的操作。



将调用Class'GetTitleValue()过程来检查匹配的字符串。



感谢您的反馈。



Hey guys,
I've done a little bit of searching for this but I'm either not finding the answer or simly not understanding it.

Several instance of a particular class are use in my application. All instances have A String property [Title] that needs to remain unique. To do this, I've decided to add a number Property
to the class and increment it when a title is set to the same value as another instance of this
Class.
In order to that, I need to count every instance of the class that contains the same value for [title_]

Please examine the fallowing code under HELP


Ultimately I'm planning on listing all of these instances for the user the choose from.

I know there is a way to gather open forms in the application under System.windows.application.Openforms And then check form type using gettype()but I'm not sure
if it's possible to do the same with class instances.

The Class' GetTitleValue() Procedure will be called to check for matching strings.

Thank you for all feedback.

Public Class MyClass

 Private Title_ As String = "Sample List"
 Private SimmilarlyNamedInstanceNumber as integer = 0

    Public Property Title() As String
        Set(NewTitle As String)
            Dim cnt As Integer = 1


               '-------------  HELP  ------------------
               'Need to count the number of instances of this class
               'That have the same [Title] Value (ignoring Casing)
               'and set SimmilarlyNamedInstanceNumber as that value + 1
               '------------ End Help ------------------


            Title_ = NewTitle
        End Set
        Get
           'Return The Name of this Instance and Unique Number for the name
            Return Title_ & " " & SimmilarlyNamedInstanceNumber.ToString
        End Get

   'Used to return the un-altered title value of the class in order to check for duplicates.
   Public Function GetTitleValue() as string
      Return Title_
   End Sub
end class

推荐答案

比这更简单。你需要一个静态字段作为计数器,并确保让所有构造函数递增它,并且析构函数递减它(注意垃圾收集器) - 但是在我看来你不需要这个后面部分。

c#模板如下:

It is simpler than that. You need a static field as counter, and be sure to make all constructors increment it, and the destructor decrement it (be aware of the garbage collector) - but this later part is not needed in you case as I see.
The c# template is the follwoing:
class MyClass
{
    static int counter = 0;

    public MyClass()
    {
        Interlocked.Increment(ref counter);
    }

    public ~MyClass()
    {
        Interlocked.Decrement(ref counter);
    }
}



VB.NET版本将是:


The VB.NET version would be:

Class [MyClass]
    Shared counter As Integer = 0

    Public Sub New()
        Interlocked.Increment(counter)
    End Sub

    Protected Overrides Sub Finalize()
        Try
            Interlocked.Decrement(counter)
        Finally
            MyBase.Finalize()
        End Try
    End Sub
End Class





由于垃圾收集器相同,列表部分有点复杂( source [ ^ ])



The list part is a little bit more complicated because of the same garbage collector (source[^])

public class MyClass
{
    private static List<WeakReference> instances = new List<WeakReference>();

    public MyClass()
    {
         instances.Add(new WeakReference(this));
    }

    public static IList<MyClass> GetInstances()
    {
        List<MyClass> realInstances = new List<MyClass>();
        List<WeakReference> toDelete = new List<WeakReference>();

        foreach(WeakReference reference in instances)
        {
            if(reference.IsAlive)
            {
                realInstances.Add((MyClass)reference.Target);
            }
            else
            {
                toDelete.Add(reference);
            }
        }

        foreach(WeakReference reference in toDelete) instances.Remove(reference);

        return realInstances;
    }
}



但是如果列表的使用让你更简单就可以更简单。



[更新:工作示例]


But can be simpler if the usage of the list let's you make it simpler.

[Update: working exampe]

using System;
using System.Collections.Generic;
using System.Linq;

namespace listed
{
	public class MyClass
	{
		#region instance collection
		private static List<WeakReference> instances = new List<WeakReference>();
		
		public IList<WeakReference> Instances 
		{
			get 
			{
				return instances.AsReadOnly();
			}
		}
	 
	    public static IList<MyClass> GetInstances()
	    {
	        List<MyClass> realInstances = new List<MyClass>();
	        List<WeakReference> toDelete = new List<WeakReference>();
	 
	        foreach(WeakReference reference in instances)
	        {
	            if(reference.IsAlive)
	            {
	                realInstances.Add((MyClass)reference.Target);
	            }
	            else
	            {
	                toDelete.Add(reference);
	            }
	        }
	 
	        foreach(WeakReference reference in toDelete) instances.Remove(reference);
	 
	        return realInstances;
	    }
	    #endregion
	    
	    #region instance specific
	    public int instanceIndex { get; private set; }
	    public string baseTitle { get; private set; }
	    
	    public string Title 
	    {
	    	get 
	    	{
	    		return string.Format("{0}{1}", this.baseTitle, this.instanceIndex);
	    	}
	    }
	    
	    public MyClass(string title) 
	    {
	        this.baseTitle = title;
	        this.instanceIndex = instances.Count(x => ((MyClass)x.Target).baseTitle == title) + 1;
	        	
	    	instances.Add(new WeakReference(this));
	    }
	    #endregion
	}
	
	class Program
	{
		public static void Main(string[] args)
		{
			var o1 = new MyClass("List");
			Console.WriteLine(o1.Title);
			
			var o2 = new MyClass("SampleList");
			Console.WriteLine(o2.Title);
			
			var o3 = new MyClass("List");
			Console.WriteLine(o3.Title);
			
			var o4 = new MyClass("SampleList");
			Console.WriteLine(o4.Title);
			
			var o5 = new MyClass("List");
			Console.WriteLine(o5.Title);
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}


这篇关于收集类实例的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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