派生类中的属性为null,但不在基类中

时间:2015-07-27 14:04:31

标签: c# inheritance

我有这个简单的课程:

public class MyFileInfo
{
    private string _file;
    private int _bytesSent;

    public MyFileInfo(string file)
    {

    }

    public string File
    {
        get { return _file; }
        set { _file = value; }
    }

    public int BytesSent
    {
        get { return _bytesSent; }
        set { _bytesSent= value; }
    }
}

此外,这是派生类:

public class MyFile : MyFileInfo
{
    public MyFile(MyFileInfo myFileInfo)
    {

    }

    public DoWork()
    {
        // File is null 
    }
}

派生类在constructor和我的DoWork方法中收到了基类,property文件是null,尽管在constructor中它不是null 。 我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

您没有在任何地方保存分配给构造函数参数的值:

public MyFileInfo(string file)
{
    _file = file;
}

根据您实例化,调用和打算使用派生类的方式,您还需要将参数传递给基础构造函数:

public MyFile(MyFileInfo myFileInfo)
    : base(myFileInfo.File)
{
}

答案 1 :(得分:1)

您传递基类的事实并不一定意味着您使用该类的值。您至少需要执行以下操作:

// input resizing:

// give the item a class of .multiline
// for each .multiline, create a Multiline object that has, saved to it, the textarea it was created on.

$( document ).ready( function(){
  $(".multiline").each(function(){
    new Multiline(this);
  });
});


// constructor:
function Multiline(textarea){
  var self = this;
  this.textarea = $(textarea);

  // Give the textarea "overflow: hidden;" to hide scrollbars when newline formed
  this.textarea.css("overflow", "hidden");

  this.fakeTextField = this.createFakeField(this.textarea);
  this.textarea.on('change keydown keypress keyup', function(){
    self.setHeightOfTextarea(self)
  });
}

Multiline.prototype.createFakeField = function(textarea) {  
  // Equivelant to fake = textarea.clone();
  var fake =  $('<div></div>');

  // Add the relevant CSS from the textarea so fonts match
  var css_selectors = ["width", "padding", "line-height", "font-size", "letter-spacing", "word-wrap", "border"]
  $.each(css_selectors, function(index, value){
    fake.css(value, $(textarea).css(value))
  });

  // remove multiline class to prevent another "multiline" object being built
  fake.removeClass("multiline");

  // attach invisibibly to the DOM
  fake.css("display", 'none' );
  $("body").append(fake);

  // store as multiline's "fakeTextField"
  return fake
}

Multiline.prototype.setHeightOfTextarea = function(self) {
  // Put the text in the box.
  self.fakeTextField.html( self.textarea.val() );

  self.textarea.css("min-height", self.fakeTextField.outerHeight() + "px")
}