Проблема ОП ограничена конкретной ситуацией. Название охватывает гораздо больше ситуаций.
Вот краткий обзор всех соответствующих ситуаций приведения, о которых я сейчас могу думать:
private class CBase
{
}
private class CInherited : CBase
{
}
private enum EnumTest
{
zero,
one,
two
}
private static void Main (string[] args)
{
//########## classes ##########
// object creation, implicit cast to object
object oBase = new CBase ();
object oInherited = new CInherited ();
CBase oBase2 = null;
CInherited oInherited2 = null;
bool bCanCast = false;
// explicit cast using "()"
oBase2 = (CBase)oBase; // works
oBase2 = (CBase)oInherited; // works
//oInherited2 = (CInherited)oBase; System.InvalidCastException
oInherited2 = (CInherited)oInherited; // works
// explicit cast using "as"
oBase2 = oBase as CBase;
oBase2 = oInherited as CBase;
oInherited2 = oBase as CInherited; // returns null, equals C++/CLI "dynamic_cast"
oInherited2 = oInherited as CInherited;
// testing with Type.IsAssignableFrom(), results (of course) equal the results of the cast operations
bCanCast = typeof (CBase).IsAssignableFrom (oBase.GetType ()); // true
bCanCast = typeof (CBase).IsAssignableFrom (oInherited.GetType ()); // true
bCanCast = typeof (CInherited).IsAssignableFrom (oBase.GetType ()); // false
bCanCast = typeof (CInherited).IsAssignableFrom (oInherited.GetType ()); // true
//########## value types ##########
int iValue = 2;
double dValue = 1.1;
EnumTest enValue = EnumTest.two;
// implicit cast, explicit cast using "()"
int iValue2 = iValue; // no cast
double dValue2 = iValue; // implicit conversion
EnumTest enValue2 = (EnumTest)iValue; // conversion by explicit cast. underlying type of EnumTest is int, but explicit cast needed (error CS0266: Cannot implicitly convert type 'int' to 'test01.Program.EnumTest')
iValue2 = (int)dValue; // conversion by explicit cast. implicit cast not possible (error CS0266: Cannot implicitly convert type 'double' to 'int')
dValue2 = dValue;
enValue2 = (EnumTest)dValue; // underlying type is int, so "1.1" beomces "1" and then "one"
iValue2 = (int)enValue;
dValue2 = (double)enValue;
enValue2 = enValue; // no cast
// explicit cast using "as"
// iValue2 = iValue as int; error CS0077: The as operator must be used with a reference type or nullable type
}
Объект File API FileReader работает в Chrome так же, как и в FireFox, Opera или Internet Explorer 10 (Да, работает в IE ).
Вы начинаете с объявления нового экземпляра читателя:
var reader = new FileReader();
Определите ваши обратные вызовы для различных событий :
reader.onloadend = function( ){
document.body.style.backgroundImage = "url(" + this.result + ")";
}
А затем передайте что-нибудь для чтения:
reader.readAsDataURL( file );
Fiddle: http://jsfiddle.net/jonathansampson/K3A9r/
Когда вы работаете с несколькими файлами, все немного по-другому. Хотя ясно, что нам нужно циклически перебирать итоговый FileList, нам также нужно использовать закрытие, чтобы предотвратить подделку данных файла в течение многочисленных итераций:
// Continue only if we have proper support
if ( window.FileReader ) {
// Provide our logic upon the change even of our input
document.getElementById("collection").onchange = function(){
// Couple variables for handling each file
var counter = -1, file;
// Cycle over all files
while ( file = this.files[ ++counter ] ) {
// Create a reader for this particular file
var reader = new FileReader();
// Respond to the onloadend event of the reader
reader.onloadend = (function(file){
return function(){
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = /^image/.test(file.type) ? this.result : "t9QlH.png";
document.body.appendChild( image );
}
})(file);
// Begin reading data for this file
reader.readAsDataURL( file );
}
}
}
Fiddle: http: / /jsfiddle.net/jonathansampson/jPTV3/
Несмотря на то, что FileReader доступен практически во всех современных браузерах, вы все равно хотите быть уверены, что вы не вызываете никаких шуток пользователи в старых браузерах. Прежде чем использовать FileReader, обязательно проверьте объект окна на его наличие:
if ( window.FileReader ) {
// Safe to use FileReader
}
Я должен отметить, что выполняется это в файле: /// Путь в Chrome приведет к поломке опыта. По умолчанию текущие версии Chrome не разрешают файлам: /// страницам обращаться к другим файлам. Вы можете изменить это поведение, загружая Chrome с флагом --allow-file-access-from-files
.
Обратите внимание, что этот метод разрешает доступ к файлам только для экземпляра браузера, с которым он был открыт. Если вы хотите, чтобы это было так для всех экземпляров браузера в будущем, вы можете изменить ярлык со своего рабочего стола. Просто щелкните правой кнопкой мыши ярлык Chrome и перейдите в свойства. Затем добавьте флаг в конец цели.