C# Trick - 1

1.
ThreadPool.QueueUserWorkItem(AsyncAppend, loggingEvent);
2.
Username = string.IsNullOrEmpty(Username) ? "guest" : Username;
3.
public void Until(Func<bool> condition, Action success, Action failure)
{
   var timeIsUp = DateTime.Now.AddMilliseconds(timeout);
   while (DateTime.Now.CompareTo(timeIsUp) < 0)
  { 
     if (condition())
    {
      success();
     return;
   }
   new ManualResetEvent(false).WaitOne(interval);
  }  
   failure();
}
4.
DateTime.Now.CompareTo(DateTime.Now.AddMilliseconds(timeout)) < 0
5.
public void Until(Func<bool> condition, Action failure)
{
    Until(condition, () => { }, failure);
}
6.
public static DateTime FromUnixTimestamp(this double dateTime)
{
    var datetime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(dateTime).ToLocalTime();
    return datetime;
}

7.
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
     foreach (T item in enumeration)
    {
      action(item);
     }
}

8.
public static string AsString(this byte[] byteArray)
{
     return System.Text.Encoding.UTF8.GetString(byteArray);
}

9.
public static string TruncateString(this string value, int len)
{
    return value.Length < len ? value : value.Substring(0, len);
}

10:
c# project directories

packages
src
--bin
--Properties
--obj
--Folder
--xxxxx.cs
--xxxxxx.csproj
--packages.config
build
tools
test
--bin
--test.csproj
README.md
project.sln

11:
public static object CreateInstance(Type targetType)
{
     return targetType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null).Invoke(null);
}
12:

public static object InvokeMethod(object target, string name, params object[] args)
{
     #if NETSTANDARD1_3
        return target.GetType().GetTypeInfo().GetDeclaredMethod(name).Invoke(target, args);
    #else
       return target.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, GetTypesArray(args), null).Invoke(target, args);
    #endif
}

13:
public static void SetField(object target, string name, object val)
{
target.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).SetValue(target, val);
}

14:
public static void SetProperty(object target, string name, object val, params object[] index)
{
target.GetType().GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).SetValue(target, val, index);
}

15:

// Provides a set of methods and properties that help you trace the execution of
// your code. This class cannot be inherited.
public sealed class System.Diagnostics.Trace
Trace.Listeners.Add(new TextWriterTraceListener(@"./trace.txt"));
Trace.AutoFlush = true;
Trace.WriteLine("Test Trace");

16:
System.Diagnostics.EventLog
System.Diagnostics.Debug
System.Diagnostics.Trace

17:
[Serializable]
public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary

[ThreadStatic]
private static PropertiesDictionary _dictionary;

18:
if (!(key is string))
private readonly Hashtable m_hashtable = new Hashtable();

19:
throw new NotSupportedException("This is a Read Only Dictionary and can not be modified");
throw new ArgumentException("key must be a string");

20:
[System.Security.SecurityCritical]

21:
private readonly static ThreadContextProperties xxxNotice = new ThreadContextProperties();
private readonly static ThreadContextStacks s_stacks = new ThreadContextStacks(xxxNotice);

22:
public abstract object this[string key] { get; set; }
override public object this[string key]
{
get
{
#if NETCF
PropertiesDictionary _dictionary = GetProperties(false);
#endif
if (_dictionary != null)
{
return _dictionary[key];
}
return null;
}
set
{
GetProperties(true)[key] = value;
}
}

object IDictionary.this[object key]
{
get
{
if (!(key is string))
{
throw new ArgumentException("key must be a string", "key");
}
return InnerHashtable[key];
}
set
{
if (!(key is string))
{
throw new ArgumentException("key must be a string", "key");
}
InnerHashtable[key] = value;
}
}
23:
log4net.MDC for ThreadContextVariable in Dictionary
log4net.NDC for ThreadContextStack in Stack

24:
log4net.Appender.SmtpAppender

25:
[DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern void syslog(int priority, string format, string message);

26:
public static TimeSpan operator -(DateTime d1, DateTime d2);

27:
public static event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
public static bool HasListeners => LogMessagePublished != null;
DefaultLogger = logger ?? throw new ArgumentNullException(nameof(logger));
DefaultLogger = logger != null? logger:throw new ArgumentNullException(nameof(logger));

28:
if (packet is MqttDisconnectPacket disconnectPacket)
do disconnectPacket

29:
IMQTTChannel
{
Endpoint;
IsSecureConnection;
X509Certificate2 ClientCertificate;
Task ConnectAsync(CancellationToken);
Task DisconnectAsync(CancellationToken);
Task<int> ReadAsync(byte[],offset,count,CancellationToken);
Task WriteAsync(byte[] buffer,offset,count,CancellationToken);
}

30:
await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, _options.Server, _options.GetPort(), null).ConfigureAwait(false);

posted @ 2020-04-24 09:31  iDragon  阅读(227)  评论(0编辑  收藏  举报