本文介绍了如何才能静态类从对象获得?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过一个静态类继承一个非静态类。
I am trying to inherit a non-static class by a static class.
public class foo
{ }
public static class bar : foo
{ }
和我得到:
静态类不能从类型派生。
静态类必须从派生
对象。
我怎样才能得到它的对象?
在code为C#。
推荐答案
有在派生静态类没有价值。使用继承的理由是:
There's no value in deriving static classes. The reasons to use inheritance are:
- 多态性
- code再利用
您不能得到多态性与静态类,显然,因为没有实例的动态调度(换句话说,它不喜欢你可以传递一个栏以期待foo的功能,因为你不有无的一个酒吧)。
You can't get polymorphism with static classes, obviously, because there is no instance to dynamically dispatch on (in other words, it's not like you can pass a Bar to a function expecting a Foo, since you don't have a Bar).
code重用很容易用组合物来解决:给酒吧美孚的静态实例
Code reuse is easily solved using composition: give Bar a static instance of Foo.
这篇关于如何才能静态类从对象获得?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!