mercredi 31 juillet 2019

How can I use reflection to give a string to a class

Instructions

Create an implementation of the Robot class with the following traits:

  • Name the derived class Sonny
  • Sonny's version should be 2.0.0.0
  • Sonny's greeting should be "Hello, my name is Sonny" (bonus points for using reflection)
  • Add a fourth law: "A robot may not harm humanity, or, by inaction, allow humanity to come to harm"

    [assembly: AssemblyVersionAttribute("2.0.0.0")] public class Program { public void Main() { Assembly thisAssem = typeof(Program).Assembly; AssemblyName thisAssemName = thisAssem.GetName(); Version ver = thisAssemName.Version;

    Sony sony = new Sony(ver);
    
    Console.WriteLine("Greeting: {0}", sony.Greeting());
    Console.WriteLine("Robot Version: {0}", sony.Version);
    
    List<string> laws = sony.GetLaws();
    foreach (string law in laws)
    {
        Console.WriteLine("Law #{0}: {1}", laws.IndexOf(law) + 1, law);
    }    
    } 
    }
    public class Sony : Robot
    {
    private readonly List<string> _laws = new List<string>
    {
    "A robot may not injure a human being or, through inaction, allow a human being to come to harm.",
    "A robot must obey the orders given it by human beings, except where such orders would conflict with the First Law.",
    "A robot must protect its own existence as long as such protection does not conflict with the First or Second Law.",
    "A robot may not harm humanity, or, by inaction, allow humanity to come to harm"
    };
    
    public Sony(Version version) : base(version)
    {
    Version = Version;
    }
    
    public override string Greeting()
    {
    return "Hello, my name is Sonny";
    }
    
    public override List<string> GetLaws()
    {
    return _laws;
    }
    }
    
    public abstract class Robot
    {
    private readonly List<string> _laws = new List<string>
    {
    "A robot may not injure a human being or, through inaction, allow a human being to come to harm.",
    "A robot must obey the orders given it by human beings, except where such orders would conflict with the First Law.",
    "A robot must protect its own existence as long as such protection does not conflict with the First or Second Law."
    };
    
    protected Robot(Version version)
    {
    Version = version;
    }
    
    public abstract string Greeting();
    
    public Version Version { get; set; }
    
    public virtual List<string> GetLaws()
    {
    return _laws;
    }
    
    

    }

I have completed all the tasks but I would like to get the bonus points for reflection on the greeting. How can I achieve this?





Aucun commentaire:

Enregistrer un commentaire