gpt4 book ai didi

C# 方法隐藏

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

我有一个基类,它具有将文件移动到适当文件夹的方法。有许多不同的文件具有许多不同的命名方案。每个文件的移动和文件夹创建都是相同的,但由于文件名不同,确定日期也不同。我正在尝试这样做:

public class FileBase
{
protected FileInfo _source;

protected string GetMonth()
{
// 2/3 Files have the Month in this location
// So I want this to be used unless a derived class
// redefines this method.
return _source.Name.Substring(Source.Name.Length - 15, 2);
}

public void MoveFileToProcessedFolder()
{
MoveFileToFolder(Properties.Settings.Default.processedFolder + GetMonth);
}

private void MoveFileToFolder(string destination)
{
....
}
}

public class FooFile : FileBase
{
protected new string GetMonth()
{
return _source.Name.Substring(Source.Name.Length - 9, 2);
}
}

public class Program
{
FooFile x = new FooFile("c:\Some\File\Location_20110308.txt");
x.MoveFileToProcessedFolder();
}

问题在于此代码会导致在“MoveFileToProcessedFolder”方法中调用“GetMonth”的基类版本。我认为使用“new”关键字会隐藏原始实现并允许派生实现接管。这不是正在发生的事情。显然我不理解 new 在这种情况下的目的,有人可以帮助我理解这一点吗?

谢谢。

最佳答案

将这些方法标记为虚拟方法,然后在您的派生类中覆盖它们。 New 允许您更改项目的签名,因此如果基类具有名为 void DoWork() 的方法,您可以使用 new 关键字在派生类中声明 int DoWork()。这解决了隐式调用,但您仍然可以显式调用基类方法。

使用virtual(base)和override(derived)

关于C# 方法隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5236450/

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