C# 如何从派生类获取基类实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19243057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Get Base Class Instance from a Derived Class
提问by OneSource
I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the basekeyword to access properties and methods of the Base Class (of course), but I want to use baseitself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context"error.
我不知道这是否可行,但我正在尝试从派生类中获取基类实例。在 C# 中,我可以使用base关键字来访问 Base Class 的属性和方法(当然),但我想使用base本身。尝试这样做会导致“在此上下文中使用关键字 'base' 无效”错误。
Example Code
示例代码
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
采纳答案by Matten
If you're working with an instance of the derived class, there is no base instance
.
An example:
如果您正在使用派生类的实例,则没有base instance
. 一个例子:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
What is not possible within B
:
什么是不可能的B
:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
You can do something like this:
你可以这样做:
public void Bar()
{
base.Foo();
}
And you can add another method like
你可以添加另一种方法,比如
public A GetBase()
{
return (A)this;
}
And then you can
然后你可以
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
So this GetBase()
method is probably what you want.
所以这个GetBase()
方法可能就是你想要的。
The punchline is: If you have an instance of B
, it inherits all properties and the non-overriden behaviour of A
, but it does not consist of an instance of B
which holds an (hidden but automatic) reference to an instance of A
. You can cast your B
instance to A
, but it remains to be an instance of B
.
重点是:如果您有一个 的实例B
,它会继承 的所有属性和非覆盖行为A
,但它不包含一个实例,B
该实例包含对 的实例的(隐藏但自动)引用A
。您可以将B
实例转换为A
,但它仍然是 的实例B
。
回答by jim tollan
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
这个问题还没有得到尽可能清楚的解释。但是,通常情况下,您最好使用抽象基类和方法,然后覆盖所需的方法。然后,您可以在这种情况下根据需要使用 base.method(否则您将只是启动派生类的实例)。
public abstract class foo {
public virtual void bar(){..}
}
public class footwo : foo {
public override void bar(){
// do somethng else OR:
return base.bar();
}
}
}
}
回答by Caleb
The derived instance IS the base instance. It's just one object instance in memory.
派生实例是基础实例。它只是内存中的一个对象实例。
example:
例子:
public class A : B
{
}
var thing = new A();
thing
is an instance of an A
, and is also an instance of a B
.
You could for example, write this line: B thing2 = thing;
thing
是 an 的一个实例,A
也是 a 的一个实例B
。
例如,您可以编写以下行:B thing2 = thing;
回答by Alessandro D'Andria
Well you not provide code for your question, but i supsect you want something like
好吧,您没有为您的问题提供代码,但我认为您想要类似的东西
class Base
{
public virtual void Foo()
{
Console.WriteLine("base");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("derived");
}
//// bad
//public Base MyBase
//{
// get
// {
// return base; // Use of keyword 'base' is not valid in this context
// }
//}
// work but...
public Base MyBase
{
get
{
return (Base)this;
}
}
}
But keep in mind that MyBase
is really of type Derived
但请记住,这MyBase
确实是类型Derived
new Derived().MyBase.Foo(); // output "derived"
回答by ataurrehman
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
第1点:如果要在子类中创建基类实例比它不值得。您已经可以在 child 中访问公共事物。
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
第 2 点:如果你已经初始化了子类,现在想要获取基类“实例”,那么如果它没有初始化,你怎么能得到它(因为现在基类实例不存在于物理内存中,只有子类实例在那里)?
回答by Subin Ninan
class Parent
{
private Parent _parent;
public Parent()
{
_parent = this;
}
protected Parent GetParent()
{
return _parent;
}
}
class Child : Parent
{
private Parent _parent;
public Child()
{
_parent = base.GetParent();
}
}
回答by BBQ Singular
I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.
我对他们提出的问题的解释与此处的其他答案略有不同,因此我想我会提供 0.02 美元。
// Create a "Parent" class that has some attributes.
public class Parent
{
public string attribute_one { get; set; }
public string attribute_two { get; set; }
public string attribute_three { get; set; }
}
// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
public string attribute_four { get; set; }
public string attribute_five { get; set; }
public string attribute_six { get; set; }
}
// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
attribute_one = "interesting";
attribute_two = "strings";
attribute_three = "to";
attribute_four = "put";
attribute_five = "all";
attribute_six = "together";
};
// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();
// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
// Set the values in the base class using the ones
// that were set in the derived class above.
property.SetValue(parent, property.GetValue(child));
}
The result is a new object populated with the base class properties of the child class.
结果是一个用子类的基类属性填充的新对象。