gpt4 book ai didi

c# - 如何从其父接口(interface)获取派生类的实际类型

转载 作者:IT王子 更新时间:2023-10-29 04:08:58 25 4
gpt4 key购买 nike

假设我们有这样一段代码:

IProduct product = ProductCreator.CreateProduct(); //Factory method we have here
SellThisProduct(product);

//...

private void SellThisProduct(IProduct product)
{
//.. Do something here
}

//...

internal class Soda : IProduct
{}

internal class Book : IProduct
{}

如何在方法中推断出哪个产品实际传递给了 SellThisProduct() 方法?

我认为如果我说 GetType() 或其他东西,它可能会返回 IProduct 类型。

最佳答案

GetType 获取对象的确切运行时类型。来自 documentation :

The Type instance that represents the exact runtime type of the current instance.

您还可以使用 is 来确定对象是否是特定类型的实例:

var noise = (obj is Velociraptor) ? "SKREEE!" : "<unknown>";

为什么你需要确切的运行时类型?接口(interface)的全部要点是您应该将实现细节隐藏在公共(public)接口(interface)后面。如果您需要根据类型采取操作,那是一个很大的暗示,表明您违反了它提供的封装。

一种替代方法是使用多态性:

public interface IVocalizer { string Talk(); }

public class Doorbell : IVocalizer {
public string Talk() { return "Ding-dong!" }
}
public class Pokemon : IVocalizer {
public string Talk() {
var name = this.GetType().ToString();
return (name + ", " + name + "!").ToUpper(); } // e.g., "PIKACHU, PIKACHU!"
}
public class Human : IVocalizer {
public string Talk() { return "Hello!"; }
}

由于这三种类型根本不相关,因此从通用类型继承没有意义。但是为了表示它们具有相同的发出噪音的能力,我们可以使用 IVocalizer 接口(interface),然后让每个人发出噪音。这是一种更简洁的方法:现在当您想要让它发出声音时,您无需关心对象是什么类型:

IVocalizer talker = new ???();  // Anything that's an IVocalizer can go here.

// elsewhere:
Console.WriteLine(talker.Talk()); // <-- Now it doesn't matter what the actual type is!
// This will work with any IVocalizer and you don't
// need to know the details.

关于c# - 如何从其父接口(interface)获取派生类的实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2520694/

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