我更改了代码以更适合我的项目。我所做的是这样的:
public static XmlAttributeOverrides GetXmlAttributeOverrides(Type type)
{
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
foreach (Type derived in ClassHandler.GetImplementedInterfaces(type))
{
foreach (PropertyInfo propertyInfo in derived.GetProperties())
{
XmlAttributeAttribute xmlAttributeAttribute = ClassHandler.GetCustomAttribute<XmlAttributeAttribute>(propertyInfo, true) as XmlAttributeAttribute;
if (xmlAttributeAttribute == null) continue;
XmlAttributes attr1 = new XmlAttributes();
attr1.XmlAttribute = new XmlAttributeAttribute();
attr1.XmlAttribute.AttributeName = xmlAttributeAttribute.AttributeName;
overrides.Add(type, propertyInfo.Name, attr1);
}
}
return overrides;
}
我正在尝试实现具有属性的接口的对象都具有“[XmlAttributeAttribute(SomeName)] 在它们之上。
尽管如此,当我序列化它时,它会给出相同的结果。我没有从界面获取属性值。
这就是我序列化的方式:
public static void SerializeFile(String filename, object obj, bool deleteIfExists = true)
{
if (deleteIfExists)
{
FileManager.DeleteFile(filename);
}
Type[] extraTypes = ClassHandler.GetPropertiesTypes(obj, true);
using (var stream = new FileStream(filename, FileMode.Create))
{
//XmlSerializer xmlSerialize = new XmlSerializer(obj.GetType(), extraTypes);
XmlSerializer xmlSerialize = new XmlSerializer(obj.GetType(), GetXmlAttributeOverrides(obj.GetType()), extraTypes, null, null);
xmlSerialize.Serialize(stream, obj);
}
}
我在 ClassHandler 类中使用的两种方法:
public static T GetCustomAttribute<T>(this PropertyInfo propertyInfo, bool inherit) where T : Attribute
{
object[] attributes = propertyInfo.GetCustomAttributes(typeof(T), inherit);
return attributes == null || attributes.Length == 0 ? null : attributes[0] as T;
}
public static List<Type> GetImplementedInterfaces(Type type)
{
Type[] types = type.GetInterfaces();
List<Type> lTypes = new List<Type>();
foreach(Type t in types)
{
lTypes.Add(t);
}
return lTypes;
}
类具有以下结构:
interface IAnimal
{
// Properties
// Methods
}
public abstract class Animal : IAnimal
{
// Implements IAnimal properties and methods
// This XmlElement gets written correctly when XML Serializing
// Example:
[XmlElement("AnimalAge")]
public double Age
{
get { return _age; }
set { _age = value; }
}
}
public abstract class Bird : Animal, IAttributeWings
{
// Implements Attributes common for all "Birds"
// Setting "override" here gives me error
public bool HasWings { get { return _hasWings; } set { _hasWings = value; } }
}
public class Pelican : Bird, IAttributeCanFly
{
// Implements Attributes common for all "Pelicans"
// Does not implement previous attribute IAttributeWings since Bird class does this
// Setting "override" here gives me error as well
public bool CanFly { get { return _canFly; } set { _canFly = value; } }
}
然后属性接口仅具有诸如“bool CanFly,bool hasWings”之类的属性以及此示例中特定类别的此类和其他属性。