mirror of
https://github.com/ckaczor/Common.git
synced 2026-01-20 09:35:41 -05:00
Initial commit
This commit is contained in:
45
Extensions/Extensions.cs
Normal file
45
Extensions/Extensions.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System.IO;
|
||||
using System.Runtime.Serialization.Json;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Common.Extensions
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static bool GetBitValue(this int integer, int bit)
|
||||
{
|
||||
return (integer & (1 << bit)) != 0;
|
||||
}
|
||||
|
||||
public static int SetBitValue(this int integer, int bit, bool value)
|
||||
{
|
||||
if (value)
|
||||
integer |= 1 << bit;
|
||||
else
|
||||
integer &= ~(1 << bit);
|
||||
|
||||
return integer;
|
||||
}
|
||||
|
||||
public static string ToJson<T>(this T obj) where T : class
|
||||
{
|
||||
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
|
||||
using (MemoryStream stream = new MemoryStream())
|
||||
{
|
||||
serializer.WriteObject(stream, obj);
|
||||
return Encoding.Default.GetString(stream.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
public static Task<T> WithTimeout<T>(this Task<T> task, int duration)
|
||||
{
|
||||
return Task.Factory.StartNew(() =>
|
||||
{
|
||||
bool b = task.Wait(duration);
|
||||
if (b) return task.Result;
|
||||
return default(T);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user