我正在尝试这个示例问题,我必须创建两个隐式转换运算符来从Human创建Doggy类,反之亦然。课程需要考虑到人类年是7年。有人告诉我,如果从狗年到人年,要确保年龄类型仍然是一个int(当然),并且可能需要一些明确的转换。我不知道如何定义DogToHuman.Name,DogToHuman.Age,HumanToDog.Name和HumanToDog.Age。我对编程很陌生,所以我不习惯这种格式。任何数字都可以起作用,就像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();
}
}
对于任何混淆感到抱歉,我不仅仅是在寻找答案,而是在寻找如何解决这个问题。
答案 0 :(得分:1)
你在问题中几乎自己回答了这个问题。如果您搜索" .net隐式转换"您将打开此页面(http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx),其中显示了如何创建隐式类型转换。基于此,我按如下方式修改了类:
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 );
}
}
然后你可以像这样使用它:
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();
重点是转换是隐式,你只需要将一种类型分配给另一种,转换就会神奇地发生。
答案 1 :(得分:1)
将ConversionQuestion类更改为以下内容:
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 :(得分:0)
我并不完全清楚你在问什么,但听起来你只想要一种方法来实例化你的类并将它们传递给一些可以转换它们年龄的方法。
如果没有为您编写所有代码,可以使用以下方法。根据需要修改......
class ConversionQuestion
{
static void Main(string[] args)
{
Human human = ... // create an instance of Human, supply name and age
Doggy doggy = ... // create an instance of Doggy, supply name and age
Console.WriteLine("As a Human, {0} would be {1}", doggy.Name, DogToHumanConversion(doggy.Age));
Console.WriteLine("As a Dog, {0} would be {1}", human.Name, HumanToDogConversion(human.Age));
Console.ReadLine();
}
private int DogToHumanConversion(int dogAge)
{
// convert dog age to human
// return human age
}
private int HumanToDogConversion(int humanAge)
{
// convert human age to dog
// return dog age
}
}