什么时候在C#/.NET中使用“对象"? [英] When do I use 'object' in C#/.NET?

查看:39
本文介绍了什么时候在C#/.NET中使用“对象"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The only time I tried to use object was List<object> and I regretted it and rewrote it. I can never find an instance to use object rather than an interface. When does one use object in .NET?

推荐答案

坦白说,您真正需要它并不经常发生.但是,当您这样做时,这是显而易见的.反射,泛型转换,序列化或标记是最终导致对象混乱的话题.

Frankly, it doesn't happen often that you REALLY need it. But when you do, it's pretty obvious. Reflection, generic type casting, serialization or tagging are among topic that ends up having object around.

这就像 void * ...,本质上几乎是一样的.您想知道这种粗暴"物品有什么用,直到您陷入困境,只能使用它.

It's like void*... which in essence is almost the same. You wonder what's the use for such "crude" item until you ends up in a corner with no way out, but to use it.

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

It's the lowest level you can find in managed code. Everything is an object, you cannot go deeper.

通用类型转换:

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.
}

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

"Tags" of the idea of assigning an item to a generic container who has no idea of the content:

public class DragDropWrapper
{
    private object tag;

    public object Tag
    {
        get { return tag; }
    }
}

拖动了什么?不知道.可以是任何东西.

What is dragged? No idea. Can be anything.

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

Or the very common Event Sender:

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

发件人可以是任何东西.

The sender can be anything.

反射以扩展对象的属性:

Reflection to expand the property of an object:

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;
}

还有更多的可能性.

这篇关于什么时候在C#/.NET中使用“对象"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆