У меня есть произвольное количество классов, classThatInherits
, anotherClassThatInherits
и т. Д., Которые наследуют classToBeInherited
. У меня тогда есть метод, b
, который должен иметь доступ к myValue
из классов, наследующих classToBeInherited
. Как я могу достичь этого без кастинга?Получить переменную из класса, который наследует другой
//This class will be inherited by other classes
public class classToBeInherited {
public bool isSomething { get; set; }
}
//This class with inherit 'classToBeInherited'
public class classThatInherits : classToBeInherited {
public int myValue { get; set; } //this needs to be accessable...
}
//...And so will this class
public class anotherClassThatInherits : classToBeInherited {
public int myValue { get; set; }
}
private class normalClass {
private void a() {
classThatInherits cti = new classThatInherits();
b(cti);
anotherClassThatInherits acti = new anotherClassThatInherits();
b(acti);
}
private void b(classToBeInherited c) {
//***
//get myValue from the classes that inherit classToBeInherited
//***
}
}
Из любопытства, есть ли причина, по которой myValue не может быть членом классаToBeInherited? Поскольку функция b() ожидает аргумент типа classToBeInherited, кажется, что myValue должен быть частью этого типа. – chijos
Ну, если классThatInherits может получить к нему доступ, это будет нормально ... – bwoogie
Да. Любой унаследованный класс может обращаться к общедоступным свойствам родительского класса. Поэтому я также думаю, что вам нужно объявить myValue в classToBeInherited. Любое функциональное ограничение не делать этого? Если нет, вам нужно сделать кастинг, чтобы это сделать. –