我创建了一个using()而没有指定对象名.
我的问题是如何访问我的新对象并打印其名称?
class Program
{
static void Main(string[] args)
{
AnimalFactory factory = new AnimalFactory();
using (factory.CreateAnimal())
{
Console.WriteLine("Animal {} created inside a using statement !");
//How can i print the name of my animal ?? something like this.Name ?
}
Console.WriteLine("Is the animal still alive ?");
}
}
public class AnimalFactory
{
public IAnimal CreateAnimal()
{
return new Animal();
}
}
public class Animal : IAnimal
{
public string Name { get; set; }
public Animal()
{
Name = "George";
}
public void Dispose()
{
Console.WriteLine("Dispose invoked on Animal {0} !", Name);
Name = null;
}
}
public interface IAnimal : IDisposable
{
string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)
你为什么要那样做?如果您想在此处访问该对象,您应该获得对它的引用.(假设您的示例代表了您尝试解决的问题).
using (Animal a = factory.CreateAnimal())
{
Console.WriteLine("Animal {0} created inside a using statement !", a.Name);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |