Is there an easier way to give a function an alias name in C#

若如初见. 提交于 2019-12-11 03:47:49

问题


BACKGROUND: In the API I am porting, there are a large number of functions prefixed with sqlite3_. They are encapsulated in a class named Sqlite3, so the function call is Sqlite3.sqlite3_...

I've created a number of alias calls, similar to the following,

//C# alias for call    
public static void result_error_toobig(sqlite3_context pCtx)
{ sqlite3_result_error_toobig(pCtx); }

//Native call   
public static void sqlite3_result_error_toobig(sqlite3_context pCtx)
{
  Debug.Assert(sqlite3_mutex_held(pCtx.s.db.mutex));
  pCtx.isError = SQLITE_ERROR;
  setResultStrOrError(pCtx, "string or blob too big", -1,
  SQLITE_UTF8, SQLITE_STATIC);
}

This allows me to write code, like Sqlite3.result_error_toobig(pCtx);

QUESTION:

  • Will the compiler optimize the call, so the overhead is minimal?
  • Is there an easier way to create this type of alias?

回答1:


One time saver you could employ is using public delegate fields rather than creating methods for each function. As long as the parameter signatures are the same, you could do something like this:

public static class Sqlite3
{
    public static Action<sqlite3_context> ResultErrorTooBig =
        sqlite3_result_error_toobig;
    public static Func<T1, T2> AnotherMethod = 
        sqlite3_another_method;
}

Edit:

If you need to pass parameters by reference, you probably can't use those convenient Action and Func classes. However, you can declare your own delegate types, like this:

delegate int StatementDelegate(ref sqlite3_stmt pStmt);

Then, in your static Sqlite3 class, you could do something like this:

public static StatementDelegate Finalize = sqlite3_finalize;



回答2:


Will the compiler optimize the call, so the overhead is minimal?

Yes, the compiler will optimize the call and effectively remove your wrapper method. Edit: in release mode it will get optimized, debug mode will not.

Is there an easier way to create this type of alias?

Depending on the number of aliases you need to create, you could write a macro in Visual Studio to do the repetative work for you. Just depends on if it will take longer to write the macro or not.

pk



来源:https://stackoverflow.com/questions/2315468/is-there-an-easier-way-to-give-a-function-an-alias-name-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!