首页 \ 问答 \ C#Image / Bitmap Superclass / Subclass Casting anomaly(C# Image/Bitmap Superclass/Subclass Casting anomaly)

C#Image / Bitmap Superclass / Subclass Casting anomaly(C# Image/Bitmap Superclass/Subclass Casting anomaly)

我正在阅读C#Image类。 这个类是抽象的。 因为它是一个抽象类,我不能创建一个对象,但它有一个方法Image.FromFile(string path); 返回一个Bitmap对象。 现在在代码中, Image img = Image.FromFile(path)可以工作,但Bitmap img = Image.FromFile(path)不行。 但是, Bitmap img = (Bitmap) Image.FromFile(path)确实有效!

我的问题是:如果方法返回类型是Bitmap,为什么我需要显式转换为Bitmap? 到底是怎么回事?

澄清一下:我知道MSDN文档说该方法返回一个Image。 当我使用断点检查时,图像包含一个位图。 即使它确实持有一个Image,这对我来说会更加混乱,因为Image是抽象的,所以我不可能拥有一个Image对象,不是吗? 我错过了一些明显的东西吗?


I was reading up on C# Image class. This class is abstract. Being as it is an abstract class, I can not make an object out of, but it has a method Image.FromFile(string path); that returns a Bitmap object. Now in the code, Image img = Image.FromFile(path) works, but Bitmap img = Image.FromFile(path) does not. However, Bitmap img = (Bitmap) Image.FromFile(path) does work!

My question is this: Why do I need to explicit cast to Bitmap if the method return type is Bitmap? What is going on?

To clarify: I know that MSDN docs say that the method returns an Image. When I use a breakpoint to check, the Image holds a Bitmap. Even if it did hold an Image, this would be even more confusing for me, as Image is abstract, so I can't possibly have an Image object, no? Am I missing something obvious here?


原文:https://stackoverflow.com/questions/26974726
更新时间:2023-09-22 21:09

最满意答案

我会去找一个sep。 过滤功能:

// data is your location data (used in the filter method)
// might be better to remove this from global namespace.
var data = [{
  "city": "Houston",
  "country": "United States",
  "region": "Texas"
}];


/* @param filterBy the key for your ojects (city, country)
 * @param filterVal the value to check for
 */
function filterData( filterBy, filterVal) {
  return data.map(function(row) {return row}).filter(function(value) {
      if(value[filterBy] == filterVal) {
        return true;
      }
      return false;
  });
}

此功能可用于根据每个选择获取所有三个字段的过滤数组。 以下jquery代码是未经测试的,更多伪代码用于演示如何使用过滤器:

$(".form-control select").on('change', function() {
    // using the field id as object-key.
    // second, call filterdata with the key and the current val.
    var identifier = this.id,
        fData = filterData( identifier, $(this).val());

    // now all you need to do is to loop over all your fields
    // and update all select fields by using the filtered Data..
    $(".form-control select").each(function() {
        var cid = this.id, c = '', 
        emptyText = $(this).find("option[value='']").text();
        // get the 'Please Select' for each field
        c += '<option value="">' + emptyText + '</option>';
        // loop over all available data elements of the filtered data
        // if the object-key is the same as current id, 
        // add a selection...
        for( var i=0, l = fData.length; i < l; i++) {
          foreach( prop in fData[i]) {
            if (prop == cid) {
              c +="<option value="+"'"+fData[i][cid]+"'"+">"+
                fData[i][cid]+"</option>";
            }
          } 
        }
        $(this).html(c);
    });
});

正如我所说,jQuery代码未经测试,但您可以通过直接调用它来轻松验证过滤器方法,例如:

console.log(filterData( 'city', 'Roseland'));
console.log(filterData( 'region', 'New Jersey'));
console.log(filterData( 'country', 'United States'));

除此之外,由于下面的注释,这里是另一种可以一次处理所有字段值的过滤方法。 您需要做的就是收集所有字段(及其键)的当前值,将其存储在对象中,filter方法将返回匹配的数据。 conditionAll是一个布尔标志,用于决定所有过滤器是否必须匹配(true)或仅一个(false)。

function multiFilterData( filters, conditionAll ) {
  return data.map(function(row) {return row}).filter(function(value) {
    for(var key in filters) {
      if( conditionAll && value[key] != filters[key]) {
        return false;
      } else if( !conditionAll && value[key] == filters[key]) {
        return true;
      }
    }
    return (conditionAll) ? true : false;
  });
}


// all conditions must fit (this won't work in many cases)
console.log(multiFilterData( {city:'Roseland',region:'-', country:'-'}, true ));
// one condition must fit
console.log(multiFilterData( {city:'Roseland',region:'-', country:'-'}, false ));

I finally used lodash to filter the json data. It made my task very easy and straight forward. I just created a function as follows and called it on change of every dropdown. The function below is taking the selected value from each dropdown and is passing it to _filter method provide by lodash. It now gives back the filter, limited json data which matches the passed value. Later on i am iterating on that to generate the markup and injecting it to the document. At the same time, i am keeping the selectedValue unchanged on every dropdown by setting it back.

function filterDropDown(ddVals){

    var selCity = $('#city').find(":selected").val();
    var selRegion = $('#region').find(":selected").val();
    var selCountry = $('#country').find(":selected").val();


    var selData = {};

    if( selCity !== "none"){
        selData['city'] = selCity;
    } 
    if(selRegion !== "none"){
        selData['region'] = selRegion;
    }
    if(selCountry !== "none"){
        selData['country'] = selCountry;
    }




    var filteredObj = _.filter(ddVals, selData);


    var ddCountries = [];
    var ddRegions = [];
    var ddCities = [];


    $.each(filteredObj, function(i,val){

        if(ddCountries.indexOf(val.country) == -1){
            ddCountries.push(val.country);
        }

        if(ddRegions.indexOf(val.region) == -1){
            ddRegions.push(val.region);
        }

        if(ddCities.indexOf(val.city) == -1){
            ddCities.push(val.city);
        }


    });

    if(ddCountries.length > 0){
        var countries = "<option value='none'>    Select Country </option>";
        $.each(ddCountries, function(i,val){
                countries += "<option value="+"'"+val+"'"+">"+val+"</option>";
        });
        $("#country").html(countries);
        $("#country option[value='"+selCountry+"']").prop('selected', true);
    }
    if(ddRegions.length > 0){
        var regions = "<option value='none'>    Select Region </option>";
        $.each(ddRegions, function(i,val){
                regions += "<option value="+"'"+val+"'"+">"+val+"</option>";
        });
        $("#region").html(regions);
        $("#region option[value='"+selRegion+"']").prop('selected', true);
     }
     if(ddCities.length > 0){
        var cities = "<option value='none'>    Select City </option>";
        $.each(ddCities, function(i,val){
             cities += "<option value="+"'"+val+"'"+">"+val+"</option>";
        });
        $("#city").html(cities);
        $("#city option[value='"+selCity+"']").prop('selected', true);
     }


}  

相关问答

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)