Answer the question
In order to leave comments, you need to log in
How to prevent subclasses from overriding a superclass method in C#?
I want to create objects that modify the string passed to them. At the same time, it is necessary that none of them forget to check whether the string is empty and whether it was passed at all.
=> I create a base abstract class that has two methods:
* Modify, which encapsulates this check and calls MakeTransform if the check
passes * MakeTransform is a method that directly performs the transformation. It is implemented by descendants
public abstract class Modifier
{
public string Modify(string str)
{
if (str == null || str.Length == 0)
throw new ArgumentNullException("Ошибка модификатора. Строка пустая.");
return MakeTransform(str);
}
protected abstract string MakeTransform(string str);
}
public class RegexModifier : Modifier
{
private string _pattern;
public RegexModifier(string pattern)
{
_pattern = pattern;
}
protected override string MakeTransform(string source)
{
return Regex.Match(source, _pattern).Value;
}
public string Modify(string source)
{
return source;
}
}
class Program
{
static void Main(string[] args)
{
var rmod = new RegexModifier(@"[ \p{L}]*");
Console.WriteLine(rmod.Modify("Hello World321")); // Вместо ожидаемого Hello Wolrd получаем исходную строку
}
}
Answer the question
In order to leave comments, you need to log in
Well, firstly, this is a warning about the fact that one method "closes" another method with its name.
Go to project settings and set :
By default in each new project, it should be true. all C# warnings (even according to the documentation) are developer errors.
On the problem: there are no ways to disable name overlap. You can write Roslyn analytics to find such overlaps, you can check at runtime that the descendant does not have the same method.
which would not have happened if I had a mechanism at compile time to prevent overriding the parent Modify method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question