简体   繁体   English

重载方法调用重载方法

[英]Overloaded method calling overloaded method

I have a method that I'm writing that is calling another overloaded method inside it. 我有一个正在编写的方法,该方法正在其中调用另一个重载方法。 I'd like to only write one outer method, since the parameter to the outer method is being passed to the inner one. 我只想编写一个外部方法,因为外部方法的参数正在传递给内部方法。 Is there a way to do this? 有没有办法做到这一点?

I tried using generics, but I don't know enough about this so it isn't working: 我尝试使用泛型,但对此了解不足,因此无法正常工作:

public void OuterMethod<T>(T parameter)
{
    InnerMethod(parameter); // InnerMethod accepts an int or a string
}

I know that I can do this: 我知道我可以这样做:

public void OuterMethod(string parameter)
{
    InnerMethod(parameter);
}

public void OuterMethod(int parameter)
{
    InnerMethod(parameter);
}

But I'd rather do this the right way instead of copying/pasting code. 但是我宁愿以正确的方式执行此操作,而不是复制/粘贴代码。 What's the best way to accomplish this? 做到这一点的最佳方法是什么?

You can do this in C++ but not in C# (unless the inner method can also be generic instead of overloaded). 您可以在C ++中执行此操作,但不能在C#中执行此操作(除非inner方法也可以是泛型而不是重载)。


Alternatively (if you won't take 'no' for an answer), you can do a run-time switch on type, like for example ... 或者(如果您不会回答“ no”),则可以在运行时打开类型,例如...

public void OuterMethod(object parameter)
{
    if (parameter is int)
        InnerMethod((int)parameter);
    else if (parameter is string)
        InnerMethod((string)parameter);
    else
        throw new SomeKindOfException();
}

... but obviously this is a run-time, not a compile-time check. ...但是显然这是运行时,而不是编译时检查。

But I'd rather do this the right way instead of copying/pasting code. 但是我宁愿以正确的方式执行此操作,而不是复制/粘贴代码。

You can also write software to write your outer methods (eg using System.CodeDom classes) instead of writing them by hand, but this is probably more trouble than it's worth. 您也可以编写软件来编写外部方法(例如,使用System.CodeDom类),而不是手工编写它们,但这可能比其价值更大。

Like the others said, you can't really do what you are trying to do and the option you stated in your question is the best bet. 就像其他人说的那样,您实际上无法做您想做的事情,而您在问题中陈述的选择是最好的选择。

You would actually have to convert the value if you use the generic. 如果使用泛型,则实际上必须转换该值。 Otherwise you can downcast by accepting an Object as ChrisW suggests. 否则,您可以按照ChrisW的建议通过接受对象来沮丧。

 public void OuterMethod<T>(T parameter) 
            {
                T temp = parameter;
                if (temp is string )
                    InnerMethod(Convert.ToString(temp));
                if (temp is int)
                    InnerMethod(Convert.ToInt32(temp));// InnerMethod accepts an int or a string
            }

Here is a link to the overview of Generics: http://msdn.microsoft.com/en-us/library/ms172193.aspx 这是泛型概述的链接: http : //msdn.microsoft.com/zh-cn/library/ms172193.aspx

You can use a dynamic type to defer the overload resolution until run-time. 您可以使用dynamic类型将重载分辨率推迟到运行时。

public void OuterMethod(dynamic parameter)
{
    InnerMethod(parameter);
}

public void InnerMethod(int parameter) { }
public void InnerMethod(string parameter) { }

Caveat Expressions of type dynamic are not resolved or type checked by the compiler. 注意 :动态类型的 警告 表达式不能由编译器解析或检查。 And there might be a performance penalty as well. 而且还可能会降低性能。

From your description this seems like over-optimization. 从您的描述来看,这似乎是过度优化。

How about: 怎么样:

public void OuterMethod(string parameter)
{
    InnerMethod(parameter);
}

public void OuterMethod(int parameter)
{
    InnerMethod(parameter**.ToString()**);
}

If OuterMethod always calls InnerMethod, and InnerMethod only accepts an int or string, then OuterMethod<T> doesn't make any sense. 如果OuterMethod始终调用InnerMethod,而InnerMethod仅接受一个int或字符串,则OuterMethod <T>没有任何意义。

If the only difference is that one calls InnerMethod(int) and the other calls InnerMethod(string) you could do something like this: 如果唯一的区别是一个调用InnerMethod(int),另一个调用InnerMethod(string),则可以执行以下操作:

public void OuterMethod(string parameter)
{
    InnerMethodA(parameter);
}

public void OuterMethod(int parameter)
{
    InnerMethodA(parameter);
}

private void InnerMethodA(object parameter)
{
    // Whatever other implementation stuff goes here

    if (parameter is string)
    {
        InnerMethodB((string) parameter);
    }
    else if (parameter is int)
    {
        InnerMethodB((string) parameter);
    }
    else
    {
        throw new ArgumentException(...);
    }
}

private void InnerMethodB(string parameter)
{
    // ...
}

private void InnerMethodB(int parameter)
{
    // ...
}

Ok I have a similar situation, its an access control method in my business logic. 好的,我也有类似的情况,这是我的业务逻辑中的一种访问控制方法。

There is a save function that could be applied to any of my persistance layer objects. 有一个保存功能可以应用于我的任何持久层对象。

so that looks like this 所以看起来像这样

public static Save<T>(AccessControl.User user,T entity) where T:PersistanceLayerBaseClass
{
    if(CanWrite(user, entity))
    {
        entity.save();
    }
    else
    {
        throw new Exception("Cannot Save");
    }
}

How ever I have some custom code for certain entities in terms of Access Control so I wrote the following, it looks for a method more suitable to the question using System.Reflection, "can this entity be written by this user?" 我如何在访问控制方面为某些实体提供一些自定义代码,所以我写了以下内容,它使用System.Reflection寻找一种更适合该问题的方法,“该实体可以由该用户编写吗?”

public static Boolean CanWrite<T>(AccessControl.User user, T entity) where T : PersistanceLayerBaseClass
        {
            int? clubId = null;
            MethodInfo methodInfo = entity.GetType().GetMethod("CanWrite", new Type[] { typeof(AccessControl.User), entity.GetType() });
            if(methodInfo != null)
            {
                return (Boolean)methodInfo.Invoke(null, new object[] { user, entity }) ;
            }
            else 
            {
                //generic answer
            }
            return HasRole(user.UserID, "Administrator") || (clubId.HasValue && user.MemberObject.ClubId == clubId.Value && HasRole(user.UserID, "AdministerClub"));
        }

Now every time I add or remove a method, I only have to add or remove it in one place 现在,每次添加或删除方法时,只需在一个地方添加或删除方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM