Skip to main content
 首页 » 编程设计

c#之返回一个与声明的结构不同的结构,为什么它可以正确 C#

2024年08月12日55linjiqin

我正在阅读这段代码:

private static WaveFormat WaveFormatFromBlob(Blob blob){ 
 if(blob.Length == 40) 
    return (WaveFormatExtensible)Marshal.PtrToStructure(blob.Data, typeof(WaveFormatExtensible));                 
 return (WaveFormat)Marshal.PtrToStructure(blob.Data, typeof (WaveFormat)); 
} 

如果返回值声明为 WaveFormat,我如何返回 WaveFormatExtensible?而下一个问题就是:在调用例程中,如何区分返回给我的是哪种类型,并选择相应的赋值?我需要更改一个或另一个中的参数,具体取决于它是什么类型。我知道这是基本的 C#,但我就是不明白。

请您参考如下方法:

根据 this , WaveFormatExtensible 是 WaveFormat 的子类型:

public class WaveFormatExtensible : WaveFormat 

所以,你看到的叫做Liskov Substitution Principle :

Substitutability is a principle in object-oriented programming. It states that, in a computer program, if S (WaveFormatExtensible) is a subtype of T (WaveFormat), then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

因为 WaveFormatExtensible 派生自 WaveFormat,所以它有资格作为该方法的返回类型。