我有一个包含许多属性的非静态类
private static List<FileClass> FileClassList = new List<FileClass>();
internal void AddFile(Alphaleonis.Win32.Filesystem.FileInfo finfo)
{
this.FileID = FileIDCounter;
this.Name = finfo.Name;
this.FullName = finfo.FullName;
this.Attributes = GetFileAttributes(finfo);
this.CreationTime = finfo.CreationTime;
this.Extension = finfo.Extension;
this.isReadOnly = finfo.IsReadOnly;
this.LastAccessTime = finfo.LastAccessTime;
this.LastWriteTime = finfo.LastWriteTime;
this.Length = finfo.Length;
Interlocked.Increment(ref FileIDCounter); // As a Static value this is shared amongst all the instances of the class
// Interlocked.Increment is the Thread Safe way of saying FileIDCounter ++;
FileClassList.Add(this);
if (FileClassFileAdded != null) FileClassFileAdded(this);
}
虽然类是添加的 FileClassList.Add(this);但最终结果是一个 FileClassList,里面填充了类的最后一个实例所包含的任何内容,而不是 this。属性值。
那么,如何将FileClass的当前实例添加到FileClassList中,以便FileClassList的内容包含FileClass的不同实例。
这是您的问题最有可能是什么...
有这个:
internal void AddFile(Alphaleonis.Win32.Filesystem.FileInfo finfo)
在某个地方你可能做:
MyClassWhichAddsAFile cls = new MyClassWhichAddsAFile();
cls.AddFile(fileInfo1);
cls.AddFile(fileInfo2);
cls.AddFile(fileInfo3);
虽然您需要做(在此设计下):
MyClassWhichAddsAFile cls1 = new MyClassWhichAddsAFile();
cls1.AddFile(fileInfo1);
MyClassWhichAddsAFile cls2 = new MyClassWhichAddsAFile();
cls2.AddFile(fileInfo2);
........
同样,我不是在讨论您的设计或如何正确完成它。我告诉你,你的问题可能是从这种情况中出来的
我认为你的设计有点歪斜。我不认为AddFile应该是FileClassList的一部分。然而,没有另一个地方可以容纳它。我会说这样做:
internal static void AddFile(Alphaleonis.Win32.Filesystem.FileInfo finfo, FileClass theClass)
{
theClass.FileID = FileIDCounter;
theClass.Name = finfo.Name;
theClass.FullName = finfo.FullName;
theClass.Attributes = GetFileAttributes(finfo);
theClass.CreationTime = finfo.CreationTime;
theClass.Extension = finfo.Extension;
theClass.isReadOnly = finfo.IsReadOnly;
theClass.LastAccessTime = finfo.LastAccessTime;
theClass.LastWriteTime = finfo.LastWriteTime;
theClass.Length = finfo.Length;
Interlocked.Increment(ref FileIDCounter); // As a Static value this is shared amongst all the instances of the class
// Interlocked.Increment is the Thread Safe way of saying FileIDCounter ++;
FileClassList.Add(theClass);
if (FileClassFileAdded != null) FileClassFileAdded(theClass);
}
更好的方法是在 FileClass 上创建一个 contrstuctor 来获取 FileInfo 并填充这些属性并像这样调用它:
var someFileClass = new FileClass(theFileInfo);
FileClass.AddFile(someClassFile);
和添加文件将是:
internal static void AddFile(Alphaleonis.Win32.Filesystem.FileInfo finfo, FileClass theClass)
{
Interlocked.Increment(ref FileIDCounter); // As a Static value this is shared amongst all the instances of the class
// Interlocked.Increment is the Thread Safe way of saying FileIDCounter ++;
FileClassList.Add(theClass);
if (FileClassFileAdded != null) FileClassFileAdded(theClass);
}
即便如此,我认为 AddFile 应该是调用者而不是被调用者的方法!