我什么时候在C#/ .NET中使用'object'?

6 .net c# object

我尝试使用对象的唯一一次是List<object>,我后悔并重写了它.我永远找不到使用对象而不是接口的实例.什么时候在.NET中使用对象?

Lig*_*ker 12

坦率地说,你真的不需要它.但是当你这样做时,这很明显.反射,泛型类型转换,序列化或标记是最终具有对象的主题.

它就像void*......本质上几乎是一样的.你想知道这种"原油"物品的用途是什么,直到你走到一个没有出路的角落,但要使用它.

这是您在托管代码中可以找到的最低级别.一切都是对象,你不能更深入.

通用类型转换:

public T AddComponents<T>()
{
    Component component = (Component)Activator.CreateInstance(typeof(T));

    if (component != null)
    {
        component.Parent = this;
        components.Add(component);
    }

    return (T)(object)component; //Cannot directly cast Component to T since we have no constraint between them.
}
Run Code Online (Sandbox Code Playgroud)

将项目分配给不知道内容的通用容器的想法的"标签":

public class DragDropWrapper
{
    private object tag;

    public object Tag
    {
        get { return tag; }
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么拖累?不知道.可以是任何东西.

或者非常常见的事件发件人:

public void Message(object sender, string text)
{
    Entry entry = new Entry(sender, EntryType.Message, text);
    AddEntry(entry);
}
Run Code Online (Sandbox Code Playgroud)

发件人可以是任何东西.

反射扩展对象的属性:

public static List<InfoNode> ExpandObject(InfoGrid grid, InfoNode owner, object obj)
{
    List<InfoNode> nodes = new List<InfoNode>();

    if (obj == null)
        return nodes;

    PropertyInfo[] infos = obj.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);

    foreach (PropertyInfo info in infos)
        nodes.Add(new PropertyNode(grid, owner, obj, info));

    nodes = nodes.OrderBy(n => n.Name).ToList();

    return nodes;
}
Run Code Online (Sandbox Code Playgroud)

还有更多的可能性.