gpt4 book ai didi

c# - 区分用于引用对象的类型及其后备存储的类型

转载 作者:太空狗 更新时间:2023-10-29 21:59:37 24 4
gpt4 key购买 nike

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();
}
}

更新:感谢 Dan Bryant 的提醒。

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 { }
}

最佳答案

您可以使用泛型类型推断:

using System;

internal interface IAnimal
{
}

internal class Cat : IAnimal
{
}

class Program
{
static void Main()
{
var cat = new Cat();
Console.WriteLine(cat.GetType()); // Cat
Console.WriteLine(GetStaticType(cat)); // Cat

IAnimal animal = cat;
Console.WriteLine(GetStaticType(animal)); // IAnimal
}

static Type GetStaticType<T>(T _)
{
return typeof (T);
}
}

关于c# - 区分用于引用对象的类型及其后备存储的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3104937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com