问题
I am trying out this example problem where I have to make two implicit conversion operators to create a Doggy class from a Human and vice versa. The classes need to take into fact that a human year is 7 dog years. I was told that if going from Dog years to human years to make sure the type of age is still an int (of course) and that it may require some explicit converting. I don't know how to define DogToHuman.Name, DogToHuman.Age, HumanToDog.Name and HumanToDog.Age. I am kind of new to programming so I am not used to this format. Any number to start with would work, Like human age of 25.
class Human
{
public string Name;
public int Age;
public Human(string name, int age)
{
Name = name;
Age = age;
}
}
class Doggy
{
public string Name;
public int Age;
public Doggy(string name, int age)
{
Name = name;
Age = age;
}
}
class ConversionQuestion
{
static void Main(string[] args)
{
Console.WriteLine("As a Human, {0} would be {1}", DogToHuman.Name, DogToHuman.Age);
Console.WriteLine("As a Dog, {0} would be {1}", HumanToDog.Name, HumanToDog.Age);
Console.ReadLine();
}
}
Sorry about any confusion, I wasn't just fishing for an answer, and was more looking for how to go about it.
回答1:
Change your ConversionQuestion class to something like this:
class ConversionQuestion
{
static void Main(string[] args)
{
Doggy dog = new Doggy("Max", 3);
Human human = new Human("Leonardo", 23);
Console.WriteLine("As a Human, {0} would be {1}", DogToHuman(dog).Name, DogToHuman(dog).Age);
Console.WriteLine("As a Dog, {0} would be {1}", HumanToDog(human).Name, HumanToDog(human).Age);
Console.ReadLine();
}
public static Human DogToHuman(Doggy dog)
{
return new Human(dog.Name, (dog.Age * 7));
}
public static Doggy HumanToDog(Human human)
{
return new Doggy(human.Name, (human.Age / 7));
}
}
回答2:
You almost answered the question yourself in your question. If you search for ".net implicit conversion" you'll turn up this page (http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx) that shows you how to create implicit type conversions. Based on that, I modified your classes as follows:
class Human
{
public string Name;
public int Age;
public Human( string name, int age )
{
Name = name;
Age = age;
}
public static implicit operator Doggy( Human human )
{
return new Doggy( human.Name, human.Age / 7 );
}
}
class Doggy
{
public string Name;
public int Age;
public Doggy( string name, int age )
{
Name = name;
Age = age;
}
public static implicit operator Human( Doggy dog )
{
return new Human( dog.Name, dog.Age * 7 );
}
}
Then you can use it like this:
Human human = new Human( "Fred", 42 );
Doggy dog = human;
Console.WriteLine( "As a Human, {0} would be {1}", human.Name, human.Age );
Console.WriteLine( "As a Dog, {0} would be {1}", dog.Name, dog.Age );
Console.ReadLine();
The whole point is that the conversion is implicit, you just need to assign one type to the other and the conversion happens magically.
来源:https://stackoverflow.com/questions/23256461/dog-to-human-years-and-vice-versa