如何获得一个派生类的实际类型从其父接口

如何获得一个派生类的实际类型从其父接口

本文介绍了如何获得一个派生类的实际类型从其父接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们有这样的code部分:

Let's say we have a code portion like this:

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()方法中的方法?

How can I infer which product is actually passed into SellThisProduct() method in the method?

我想,如果我说的GetType()或东西它可能会返回IProduct类型。

I think if I say GetType() or something it will probably return the IProduct type.

推荐答案

的GetType 让你的对象的确切运行时类型。从 documentation:

GetType gets you the exact runtime type of an object. From the documentation:

这是重新$ P $的类型实例psents当前实例的确切运行时类型。

您也可以使用来确定对象是否是一个特定类型的实例:

You can also use is to determine if an object is an instance of a specific type:

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

为什么需要确切的运行时类型有关系吗?接口的整个的一点是,你应该躲在背后的通用接口的实现细节。如果您需要根据类型采取行动,这是一个很大的提示,你违反了它所提供的封装。

Why do you need the exact runtime type, though? The entire point of an interface is that you should be hiding the implementation details behind the common interface. If you need to take an action based on the type, that's a big hint that you're violating the encapsulation it provides.

一替代方法是使用多态

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!"; }
}

由于这三种类型都没有关系,从一个共同的类型继承没有意义。但重新它们共享制造噪音的同样的能力present,我们可以使用IVocalizer界面,然后要求每个人作出的噪音。这是一个更清洁方法:现在你不需要关心,当你要问它发出噪音,什么类型的对象是:

Since these three types aren't related at all, inheritance from a common type doesn't make sense. But to represent that they share the same capability of making noise, we can use the IVocalizer interface, and then ask each one to make a noise. This is a much cleaner approach: now you don't need to care what type the object is when you want to ask it to make a noise:

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.

这篇关于如何获得一个派生类的实际类型从其父接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:42