访问using语句的对象

ila*_*sch -3 .net c#

我创建了一个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)

key*_*rdP 6

你为什么要那样做?如果您想在此处访问该对象,您应该获得对它的引用.(假设您的示例代表了您尝试解决的问题).

using (Animal a = factory.CreateAnimal())
{
   Console.WriteLine("Animal {0} created inside a using statement !", a.Name); 
}
Run Code Online (Sandbox Code Playgroud)

  • @ilansch的"最短"有什么意义?它不会使你的代码更快,并且它肯定不会使操作一个对象没有更清楚,否则代码中没有引用. (3认同)