gpt4 book ai didi

c# - 使用.NET是否可以将自定义属性分配给诸如FileSystemWatcher的内置对象?

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:50 25 4
gpt4 key购买 nike

是否可以向.NET框架中的对象添加自定义属性?

我知道如果我只是给一个类,我会写一个属性,那么该怎么做,但是向FileSystemWatcher类添加自定义属性呢?

我正在加载要从XML文件监视的路径,但是还想添加一个属性来存储更多信息,在这种情况下,该属性是配置文件的位置。我可以将此属性添加到FileSystemWatcher类本身吗?

最佳答案

因此,您想在添加属性的同时继承FileSystemWatcher的所有功能吗?
尝试继承该类:

public class MyFileSystemWatcher : FileSystemWatcher
{
public string XmlConfigPath { get; set; }
}


然后,您可以在要使用 System.IO.FileSystemWatcher的每个地方使用新类,如下所示:

MyFileSystemWatcher fsw = new MyFileSystemWatcher();
fsw.XmlConfigPath = @"C:\config.xml";
fsw.Path = @"C:\Watch\Path\*.*";




另一种方法是使一个类同时具有config文件location和FileSystemWatcher对象作为属性,它们如下:

public class MyFileSystemWatcherManager
{
public string XmlConfigPath { get; set; }
public FileSystemWatcher Watcher { get; set; }

public MyFileSystemWatcherManager()
{
Watcher = new FileSystemWatcher();
}
}


和这样的用法:

MyFileSystemWatcherManager manager = new MyFileSystemWatcherManager();
manager.XmlConfigPath = @"C:\config.xml";
manager.Watcher.Path = @"C:\Watch\Path\*.*";


即使无法继承基类,也可以进行组合,并且从OO角度来看,它通常是首选的,因为大多数使用您的类的代码将仅依赖于您的类,而不依赖于基类。但是,当您确实希望继承所有基本行为并仅添加一些(定义明确的)附加功能时,继承是更简单,更紧密耦合的解决方案。

关于c# - 使用.NET是否可以将自定义属性分配给诸如FileSystemWatcher的内置对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3335276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com