Using Script# code with string operations in standart C# .NET project

拜拜、爱过 提交于 2019-12-01 21:49:50

问题


I added reference of Script# to my standart console application. After that I was trying to invoke some method from there but was getting the following error:

I suppose it happened on the following line:

string[] lines = s.Split(';');

My assumption is that usual mscorlib library has not method public string[] Split(char separator), but has public string[] Split(params char[] separator)

Is it possible to write valid code with such string operations both for a Script# project and for a standart C# .NET project? Due to this problem I have to write duplicate code for both projects with minimal difference.

P.S. I tried to use assemblty binding redirects, as discussed in this SO question, but it didn't help me.


回答1:


EDIT: The only solution to me seems to be the extension methods. You can define extension method Split on top of Script#'s String type similar to the standard .NET String.Split, i.e. accepting params char[]. And only then you can use the same code.

string[] lines = s.Split(new char[] { ';' });

Alternatively, define extension on top of standard String type, in case Script# is strict on extensions. But I think should not be a problem since extension method is just a static method.

OLD ANSWER: After realizing that Script# does not accept params char[], below answer became incorrect:

You are invoking s.Split by passing char to it. However, this method accepts params char[]. Although C# compiler allows you to pass char to Split, it later compiles it into passing char[]. So, if you want to have the same code working for both Script# and C#, change your code to the following way:

string[] lines = s.Split(new char[] { ';' });

This will work for both Script# and C#.




回答2:


I found solution!

My sequence of actions:

  1. Create Split method of string splitting in any Script# class.

  2. Define conditional compilation symbol DOTNET in your .NET project.

  3. Add As Link file with Split method from Script# to .NET project and also add as link another necessary dependent files.

public static string[] Split(string str, string separator)
{
    string[] result;
#if DOTNET
    result = str.Split(new string[] { separator }, System.StringSplitOptions.None);
#else
    result = str.Split(separator);
#endif
    return result;
}

After that appropriate code will be selected dependent on DOTNET symbol, which defined only in .NET project. Other similar methods, not only with strings, can be rewritten in the same way.



来源:https://stackoverflow.com/questions/13260153/using-script-code-with-string-operations-in-standart-c-sharp-net-project

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