Я работал над некоторыми из этих образцов и обнаружил, что в некоторых случаях их недостает. Эта версия работает со всеми типами дженериков: типами, интерфейсами и их определениями.
public static bool InheritsOrImplements(this Type child, Type parent)
{
parent = ResolveGenericTypeDefinition(parent);
var currentChild = child.IsGenericType
? child.GetGenericTypeDefinition()
: child;
while (currentChild != typeof (object))
{
if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
return true;
currentChild = currentChild.BaseType != null
&& currentChild.BaseType.IsGenericType
? currentChild.BaseType.GetGenericTypeDefinition()
: currentChild.BaseType;
if (currentChild == null)
return false;
}
return false;
}
private static bool HasAnyInterfaces(Type parent, Type child)
{
return child.GetInterfaces()
.Any(childInterface =>
{
var currentInterface = childInterface.IsGenericType
? childInterface.GetGenericTypeDefinition()
: childInterface;
return currentInterface == parent;
});
}
private static Type ResolveGenericTypeDefinition(Type parent)
{
var shouldUseGenericType = true;
if (parent.IsGenericType && parent.GetGenericTypeDefinition() != parent)
shouldUseGenericType = false;
if (parent.IsGenericType && shouldUseGenericType)
parent = parent.GetGenericTypeDefinition();
return parent;
}
Вот также юнит-тесты:
protected interface IFooInterface
{
}
protected interface IGenericFooInterface<T>
{
}
protected class FooBase
{
}
protected class FooImplementor
: FooBase, IFooInterface
{
}
protected class GenericFooBase
: FooImplementor, IGenericFooInterface<object>
{
}
protected class GenericFooImplementor<T>
: FooImplementor, IGenericFooInterface<T>
{
}
[Test]
public void Should_inherit_or_implement_non_generic_interface()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(IFooInterface)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface()
{
Assert.That(typeof(GenericFooBase)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_not_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
}
[Test]
public void Should_inherit_or_implement_non_generic_class()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void Should_inherit_or_implement_any_base_type()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
Взгляните на телефон iconv()
или mb_convert_encoding()
. Только между прочим: почему не делают utf8_encode()
и utf8_decode()
работа для Вас?
utf8_decode — Преобразовывает строку с символами ISO-8859-1, закодированными UTF-8 к однобайтовому ISO-8859-1
utf8_encode —, Кодирует строку ISO-8859-1 к UTF-8
Поэтому по существу
$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');
, все должны сделать то же - с utf8_en/decode()
требование никакого специального расширения, mb_convert_encoding()
требование ext/mbstring и iconv()
требование ext/iconv.
Необходимо использовать пакет iconv , конкретно его функция iconv.
В первую очередь, не используйте различную кодировку. Это приводит к путанице, и UTF-8 является определенно тем, который необходимо использовать везде.
Возможности являются Вашим входом, не ISO-8859-1, но что-то еще (ISO-8859-15, Windows 1252). Для преобразования от тех используйте iconv или mb_convert_encoding
.
Тем не менее, utf8_encode
и utf8_decode
должен работать на ISO-8859-1. Было бы хорошо, если Вы могли бы отправить ссылку на файл или кодируемую программой uuencode или base64 строку в качестве примера, для которой преобразование приводит к сбою или приводит к неожиданным результатам.
Я использовал:
function utf8_to_html ($data) {
return preg_replace(
array (
'/ä/',
'/ö/',
'/ü/',
'/é/',
'/à/',
'/è/'
),
array (
'ä',
'ö',
'ü',
'é',
'à',
'è'
),
$data
);
}
Я использую эту функцию:
function formatcell($data, $num, $fill=" ") {
$data = trim($data);
$data=str_replace(chr(13),' ',$data);
$data=str_replace(chr(10),' ',$data);
// translate UTF8 to English characters
$data = iconv('UTF-8', 'ASCII//TRANSLIT', $data);
$data = preg_replace("/[\'\"\^\~\`]/i", '', $data);
// fill it up with spaces
for ($i = strlen($data); $i < $num; $i++) {
$data .= $fill;
}
// limit string to num characters
$data = substr($data, 0, $num);
return $data;
}
echo formatcell("YES UTF8 String Zürich", 25, 'x'); //YES UTF8 String Zürichxxx
echo formatcell("NON UTF8 String Zurich", 25, 'x'); //NON UTF8 String Zurichxxx
Проверьте мою функцию в моем блоге http://www.unexpectedit.com/php/php-handling-non-english-characters-utf8