using System;
interface IAnimal
{
}
class Cat: IAnimal
{
}
class Program
{
public static void Main(string[] args)
{
IAnimal cat = new Cat();
// Console.WriteLine(cat.GetType());
// This would only give me the type of
// the backing store, i.e. Cat. Is there a
// way I can get to know that the identifier
// cat was declared as IAnimal?
Console.ReadKey();
}
}
Cập nhật: Nhờ Dan Bryant cho lời nhắc nhở.Phân biệt giữa các loại dùng để tham chiếu một đối tượng và các loại hình cửa hàng ủng hộ mình
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
namespace TypeInfo
{
class Program
{
public static void Main(string[] args)
{
IAnimal myCat = new Cat();
ReflectOnType();
Console.ReadKey();
}
public static void ReflectOnType()
{
Assembly.GetExecutingAssembly().
GetType("TypeInfo.Program").
GetMethod("Main",
BindingFlags.Static| BindingFlags.Public).
GetMethodBody().LocalVariables.
ToList().
ForEach(l => Console.WriteLine(l.LocalType));
}
}
interface IAnimal { }
class Cat : IAnimal { }
}
Có thể, nhưng bạn phải suy nghĩ về phương pháp riêng của mình; LocalVariableInfo có một LocalType bạn có thể sử dụng. Xem tại đây: http://stackoverflow.com/questions/2696691/can-i-get-the-method-local-variables-through-a-stack-trace-in-c –
Tại sao bạn muốn làm điều này khi loại có sẵn tĩnh? –
@Dan Bryant: Chết tiệt! Chỉ trích! Chỉ trích! Tôi sử dụng LocalVariableInfo và LocalType mọi lúc. Tôi lam sao vậy nhỉ? Và tôi đã sử dụng nó trong một kịch bản tương tự trước đó. Chỉ trích! Tại sao tôi hỏi câu hỏi này? Cảm ơn một triệu lời nhắc nhở. –