Вопрос

I'm trying to write an extension (actually taken from Case insensitive 'Contains(string)')

It compensates for the Turkey Test when doing string comparison. The extension itself is simple:

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
  return source.IndexOf(toCheck, comp) >= 0;
}

Now the key is I'm trying to figure out where/how to include this so that across the entire solution (which contains multiple projects and each project has it's own namespace and classes), it can be readily accessed by string.Contains without having to do class.string.Contains or some other way.

Say there is a project 'Util' which is included in all other projects, is there someway I can put this in Util (without a class?) so that it can be globally referenced across the solution as string.Contains?

Is this even possible? If so how?

Это было полезно?

Решение

Although I don't recommend it, you can easily achieve what you are up to by including your code in public static classes under the namespace System.

namespace System
{
   public static class CaseInsensitiveContains
   {
       public static bool Contains(this string source, string toCheck, StringComparison comp)
       {
           return source.IndexOf(toCheck, comp) >= 0;
       }
   }
}

Without static class, your extension method won't work.

After you put the above in a .cs file, you can not use String.Contains anywhere since almost all code use System namespace, which means it is kinda global ;)

Другие советы

No you can not do something like that. What you can do, you can create a utility class library and add the reference of it on other projects where you want to call or use the function like below:

namespace Utility
{
    public class StringUtil
    {
        public static bool Contains(string source, string toCheck, StringComparison comp)
        {
          return source.IndexOf(toCheck, comp) >= 0;
        }
    }
}


using Utility.StringUtil;

//call function
Contains(....);

or

using Utility;

//call function

StringUtil.Contains(....);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top