귀하의 코드에서, 당신은 당신의 자녀 클래스에서 귀하의 부모 클래스 생성자를 사용하는 방법을 묻는 것 같습니까?
이 같은 기본 생성자를 호출 할 수 있습니다
public ChildClass(string name, Feature extraFeature)
:base(name) //this initializes this class with the constructor of the base class
{
Features.Add(extraFeature); //this adds your extraFeature to the features-list.
}
allthough, 나는 완전히 당신의 질문을 이해하는 데 어려움을 겪고 않습니다. 예를 들면; 이 추가 기능을 ChildClass의 컨스트럭터로 전달해야한다면 부모 클래스에 AddFeature 메서드를 제공하는 것이 좋지 않을까요?
또는 ChildClass에 추가되는 기능이 항상 동일한 경우 (생성자 매개 변수로 필요하지 않은 경우)?
은 클래스의 이름 매개 변수이며 기능 목록은 실제로 호출 할 메소드 목록 일뿐입니다. 그렇다면; 리플렉션을 사용해 보셨습니까?
편집; 내 상황에 따라 달라질 :
public class FeatureObject
{
public String Name { get; private set; }
public Dictionary<String,String> Features { get; private set; }
public FeatureObject (string name)
{
Name = name;
Features = new Dictionary<String, String>();
Features.Add("Name",name);//just an example of a feature that all objects have
}
}
public class Fish: FeatureObject
{
public Color Color { get; private set; }
public Fish(String name, Color color)
:base(name) //initializes Name and Features as described in FeatureObject-class
{
Features.Add("Color", color.ToString());//Adds color to the features-dictionary
}
}
나는 아직도 당신이 쉽게 할 수 있다고 생각합니다.
예를 들어,이 방법은 개체의 명명 된 속성의 문자열 표현을 반환하려고합니다 :
public static String GetPropertyValue(object o, String property)
{
try
{
return o.GetType().GetProperty(property).GetValue(o, null).ToString();
}
catch(Exception)
{
return null;
}
}
을 당신이 사전 객체에 객체가있는 경우,이 같은 방법을 가져올 수 있습니다 '복사 생성자가'가능, 인수와 같은 유형의 다른 개체를 촬영 한 :
public static String GetPropertyValue(String objectName, String propertyName)
{
try
{
var o = Objects[objectName];
return GetPropertyValue(o, propertyName)
}
catch (Exception)
{
return null;
}
}
내가 부모 클래스의 생성자를 호출하고 싶지 않았다; 이미 생성 된 부모 객체를 인수로 전달하려고했습니다. 이전 답변에서 '복사 생성자'에 대해 언급했습니다. 이는 내가 확실하지 않은 것입니다. 그것은 지금 삭제 된 것으로 보이지만 그것은 제가 찾고 있던 대답이었습니다. 고마워. – Ollyver