C# 对象扩展方法

发布于 2024-10-16 07:24:25 字数 79 浏览 3 评论 0原文

在 Object 类上使用扩展方法是个好主意吗?

我想知道注册此方法是否会导致性能损失,因为它将加载到上下文中加载的每个对象上。

Is it a good idea to use an extension method on the Object class?

I was wondering if by registering this method if you were incurring a performance penalty as it would be loaded on every object that was loaded in the context.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

酸甜透明夹心 2024-10-23 07:24:25

除了另一个答案之外:

不会有性能损失,因为扩展方法是编译器功能。考虑以下代码:

public static class MyExtensions
{
    public static void MyMethod(this object) { ... }
} 

object obj = new object();
obj.MyMethod();

MyMethod 的调用将实际编译为:

MyExtensions.MyMethod(obj);

In addition to another answers:

there would be no performance penalty because extension methods is compiler feature. Consider following code:

public static class MyExtensions
{
    public static void MyMethod(this object) { ... }
} 

object obj = new object();
obj.MyMethod();

The call to MyMethod will be actually compiled to:

MyExtensions.MyMethod(obj);
苏别ゝ 2024-10-23 07:24:25

不会有性能损失,因为它不会附加到系统中的每种类型,它只能在系统中的任何类型上调用。所发生的只是该方法将显示在智能感知中的每个单个对象上。

问题是:您真的需要将其放在对象上吗,还是可以更具体。如果它需要在对象上,则将其制作为对象。

There will be no performance penalty as it doesn't attach to every type in the system, it's just available to be called on any type in the system. All that will happen is that the method will show on every single object in intellisense.

The question is: do you really need it to be on object, or can it be more specific. If it needs to be on object, the make it for object.

生生不灭 2024-10-23 07:24:25

如果您确实打算扩展每个对象,那么这样做是正确的。但是,如果您的扩展实际上仅适用于对象的子集,则应将其应用于必要的最高层次结构级别,但仅此而已。

此外,该方法仅在导入命名空间的情况下可用。

我已经扩展了 Object 来尝试转换为指定类型的方法:

public static T TryCast<T>(this object input)
{
    bool success;
    return TryCast<T>(input, out success);
}

我还重载了它以接受 success bool (如 TryParse确实):

public static T TryCast<T>(this object input, out bool success)
{
    success = true;
    if(input is T)
        return (T)input;
    success = false;
    return default(T);
}

我已经将其扩展为也尝试解析输入(通过使用ToString并使用转换器),但这变得更加复杂。

If you truly intend to extend every object, then doing so is the right thing to do. However, if your extension really only applies to a subset of objects, it should be applied to the highest hierarchical level that is necessary, but no more.

Also, the method will only be available where your namespace is imported.

I have extended Object for a method that attempts to cast to a specified type:

public static T TryCast<T>(this object input)
{
    bool success;
    return TryCast<T>(input, out success);
}

I also overloaded it to take in a success bool (like TryParse does):

public static T TryCast<T>(this object input, out bool success)
{
    success = true;
    if(input is T)
        return (T)input;
    success = false;
    return default(T);
}

I have since expanded this to also attempt to parse input (by using ToString and using a converter), but that gets more complicated.

酒儿 2024-10-23 07:24:25

在 Object 类上使用扩展方法是个好主意吗?

是的,在某些情况下,事实上这是一个好主意。在 Object 类上使用扩展方法不会造成任何性能损失。只要您不调用此方法,应用程序的性能就不会受到影响。

例如,考虑以下扩展方法,它列出给定对象的所有属性并将其转换为字典:

public static IDictionary<string, object> ObjectToDictionary(object instance)
{
    var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    if (instance != null)
    {
        foreach (var descriptor in TypeDescriptor.GetProperties(instance))
        {
            object value = descriptor.GetValue(instance);
            dictionary.Add(descriptor.Name, value);
        }
    }
    return dictionary;
}

Is it a good idea to use an extension method on the Object class?

Yes, there are cases where it is a great idea in fact.Tthere is no performance penalty whatsoever by using an extension method on the Object class. As long as you don't call this method the performance of your application won't be affected at all.

For example consider the following extension method which lists all properties of a given object and converts it to a dictionary:

public static IDictionary<string, object> ObjectToDictionary(object instance)
{
    var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    if (instance != null)
    {
        foreach (var descriptor in TypeDescriptor.GetProperties(instance))
        {
            object value = descriptor.GetValue(instance);
            dictionary.Add(descriptor.Name, value);
        }
    }
    return dictionary;
}
差↓一点笑了 2024-10-23 07:24:25

下面的示例演示了正在使用的扩展方法。

namespace NamespaceName
{
public static class CommonUtil
{
    public static string ListToString(this IList list)
    {
        StringBuilder result = new StringBuilder("");

        if (list.Count > 0)
        {
            result.Append(list[0].ToString());
            for (int i = 1; i < list.Count; i++)
                result.AppendFormat(", {0}", list[i].ToString());
        }
        return result.ToString();
    }
  }
}

以下示例演示了如何使用此方法。

var _list = DataContextORM.ExecuteQuery<string>("Select name from products").ToList();
string result = _list.ListToString();

The following example demonstrates the extension method in use.

namespace NamespaceName
{
public static class CommonUtil
{
    public static string ListToString(this IList list)
    {
        StringBuilder result = new StringBuilder("");

        if (list.Count > 0)
        {
            result.Append(list[0].ToString());
            for (int i = 1; i < list.Count; i++)
                result.AppendFormat(", {0}", list[i].ToString());
        }
        return result.ToString();
    }
  }
}

The following example demonstrates how this method can be used.

var _list = DataContextORM.ExecuteQuery<string>("Select name from products").ToList();
string result = _list.ListToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文