Here are the examples of the csharp api System.Activator.CreateInstance() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
603 Examples
19
Source : ObjectBaseFactory.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static T Create<T>(AObjectBase parent = null, params object[] datas) where T : AObjectBase
{
T aObjectBase = Activator.CreateInstance<T>();
aObjectBase.id = IdUtil.Generate();
aObjectBase.Parent = parent;
aObjectBase.InitData(datas);
ObjectBaseEventSystem.Instance.Register(aObjectBase);
ObjectBaseEventSystem.Instance.Awake(aObjectBase);
return aObjectBase;
}
19
Source : ObjectBaseFactory.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static T Create<T, P1>(AObjectBase parent, P1 p1, params object[] datas) where T : AObjectBase
{
T aObjectBase = Activator.CreateInstance<T>();
aObjectBase.id = IdUtil.Generate();
aObjectBase.Parent = parent;
aObjectBase.InitData(datas);
ObjectBaseEventSystem.Instance.Register(aObjectBase);
ObjectBaseEventSystem.Instance.Awake(aObjectBase, p1);
return aObjectBase;
}
19
Source : ObjectBaseFactory.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static T Create<T, P1, P2>(AObjectBase parent, P1 p1, P2 p2, params object[] datas) where T : AObjectBase
{
T aObjectBase = Activator.CreateInstance<T>();
aObjectBase.id = IdUtil.Generate();
aObjectBase.Parent = parent;
aObjectBase.InitData(datas);
ObjectBaseEventSystem.Instance.Register(aObjectBase);
ObjectBaseEventSystem.Instance.Awake(aObjectBase, p1, p2);
return aObjectBase;
}
19
Source : ObjectBaseFactory.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static T Create<T, P1, P2, P3>(AObjectBase parent, P1 p1, P2 p2, P3 p3, params object[] datas) where T : AObjectBase
{
T aObjectBase = Activator.CreateInstance<T>();
aObjectBase.id = IdUtil.Generate();
aObjectBase.Parent = parent;
aObjectBase.InitData(datas);
ObjectBaseEventSystem.Instance.Register(aObjectBase);
ObjectBaseEventSystem.Instance.Awake(aObjectBase, p1, p2, p3);
return aObjectBase;
}
19
Source : ObjectBaseFactory.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static T Create<T, P1, P2, P3, P4>(AObjectBase parent, P1 p1, P2 p2, P3 p3, P4 p4, params object[] datas) where T : AObjectBase
{
T aObjectBase = Activator.CreateInstance<T>();
aObjectBase.id = IdUtil.Generate();
aObjectBase.Parent = parent;
aObjectBase.InitData(datas);
ObjectBaseEventSystem.Instance.Register(aObjectBase);
ObjectBaseEventSystem.Instance.Awake(aObjectBase, p1, p2, p3, p4);
return aObjectBase;
}
19
Source : BaseResult.cs
with MIT License
from 4egod
with MIT License
from 4egod
public static T CreateFailed<T>() where T: BaseResult => Activator.CreateInstance<T>();
19
Source : Utility.Reflection.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static T New<T>()
{
return Activator.CreateInstance<T>();
}
19
Source : RadiumService.cs
with MIT License
from 99x
with MIT License
from 99x
public static T Create<T>() where T: RadiumRest.Core.Plugin.RadiumPlugin
{
return Activator.CreateInstance<T>();
}
19
Source : MyObjectPool.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public T Get()
{
T t;
if (this.m_Stack.Count == 0)
{
t = ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));
this.countAll++;
}
else
{
t = this.m_Stack.Pop();
}
if (this.m_ActionOnGet != null)
{
this.m_ActionOnGet(t);
}
return t;
}
19
Source : ContextVariableDictionaryTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private void createException<T>() where T:SmartContractBridgeException,new()
{
T t = System.Activator.CreateInstance<T>();
throw t;
}
19
Source : SimpleObjPool.cs
with MIT License
from aillieo
with MIT License
from aillieo
public T Get()
{
T item;
if (m_Stack.Count == 0)
{
if(null != m_ctor)
{
item = m_ctor();
}
else
{
item = Activator.CreateInstance<T>();
}
}
else
{
item = m_Stack.Pop();
}
m_UsedCount++;
return item;
}
19
Source : Database.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public IEnumerable<T> SelectObjects<T>(string tableName, object condition, string order, int group, params string[] columns)
{
Debug.replacedert(group < columns.Length);
object obj = System.Activator.CreateInstance<T>();
string sql = MakeSelect(tableName, condition, columns, group, order);
using (DbDataReader dr = InvokeReadQuery(sql, condition is string ? null : condition))
{
while (dr.Read())
yield return DataConverter.Convert<T>(dr, obj);
}
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(DataRow row, object obj)
{
if (obj == null)
obj = System.Activator.CreateInstance<T>();
Debug.replacedert(obj is T);
return (T)StructFromValues(obj, (s) => row.Table.Columns[s] != null ? row[row.Table.Columns[s]] : null, true, false);
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(NameValueCollection vals, object obj = null)
{
if (obj == null)
obj = System.Activator.CreateInstance<T>();
Debug.replacedert(obj is T);
return (T)StructFromValues(obj, (s) => vals[s], true, false);
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(IDictionary<string, object> vals, object obj, bool hasInternal)
{
if (obj == null)
obj = System.Activator.CreateInstance<T>();
Debug.replacedert(obj is T);
return (T)StructFromValues(obj, (k) => vals.ContainsKey(k) ? vals[k] : null, true, hasInternal);
}
19
Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static T Convert<T>(DbDataReader reader, object obj)
{
if (obj == null)
obj = System.Activator.CreateInstance<T>();
Debug.replacedert(obj is T);
return (T)StructFromValues(obj, (s) => reader.GetOrdinal(s) >= 0 ? reader.GetValue(reader.GetOrdinal(s)) : null, true, false);
}
19
Source : Database.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public IEnumerable<T> SelectObjects<T>(string tableName, object condition, params string[] columns)
{
Debug.replacedert(columns.Length > 0);
object obj = System.Activator.CreateInstance<T>();
string sql = MakeSelect(tableName, condition, columns);
using (DbDataReader dr = InvokeReadQuery(sql, condition, condition is string ? null : condition))
{
while (dr.Read())
yield return DataConverter.Convert<T>(dr, obj);
}
}
19
Source : ThrowT.cs
with MIT License
from akamsteeg
with MIT License
from akamsteeg
private static TException Create()
{
var result = Activator.CreateInstance<TException>();
return result;
}
19
Source : BlazorGrid.razor.cs
with MIT License
from Akinzekeel
with MIT License
from Akinzekeel
private TRow GetEmptyRow()
{
return EmptyRow ?? Activator.CreateInstance<TRow>();
}
19
Source : JsonSerializer.cs
with MIT License
from alelievr
with MIT License
from alelievr
public static T Deserialize< T >(JsonElement e)
{
if (typeof(T) != Type.GetType(e.type))
throw new ArgumentException("Deserializing type is not the same than Json element type");
var obj = Activator.CreateInstance< T >();
#if UNITY_EDITOR
EditorJsonUtility.FromJsonOverwrite(e.jsonDatas, obj);
#else
JsonUtility.FromJsonOverwrite(e.jsonDatas, obj);
#endif
return obj;
}
19
Source : ContainerBuilder.cs
with MIT License
from aliencube
with MIT License
from aliencube
public IContainerBuilder RegisterModule<TModule>() where TModule : Module
{
var module = Activator.CreateInstance<TModule>();
return this.RegisterModule(module);
}
19
Source : ConfigurationBinderExtensions.cs
with MIT License
from aliencube
with MIT License
from aliencube
public static T Get<T>(this IConfiguration configuration, string key = null)
{
var instance = Activator.CreateInstance<T>();
if (string.IsNullOrWhiteSpace(key))
{
configuration.Bind(instance);
return instance;
}
configuration.Bind(key, instance);
return instance;
}
19
Source : AopJsonParser.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public T Parse(string body, string charset)
{
T rsp = null;
IDictionary json;
try
{
json = JsonConvert.DeserializeObject<IDictionary>(body);
}
catch (Exception)
{
json = null;
}
if (json != null)
{
JObject data = null;
// 忽略根节点的名称
foreach (object key in json.Keys)
{
data = json[key] as JObject;
if (data != null && data.Count > 0)
{
break;
}
}
if (data != null)
{
IAopReader reader = new AopJsonReader(data);
rsp = (T)AopJsonConvert(reader, typeof(T));
}
}
if (rsp == null)
{
rsp = Activator.CreateInstance<T>();
}
if (rsp != null)
{
rsp.Body = body;
}
return rsp;
}
19
Source : FCClient.cs
with MIT License
from aliyun
with MIT License
from aliyun
public T DoRequestCommon<T>(RestRequest r) where T: IResponseBase
{
IRestResponse response = this.RestHttpClient.Execute(r);
if (response.StatusCode.GetHashCode() > 299)
{
Console.WriteLine(string.Format("ERROR: response status code = {0}; detail = {1}", response.StatusCode.GetHashCode(), response.Content));
}
T res = Activator.CreateInstance<T>();
res.SetStatusContent(response.Content, response.StatusCode.GetHashCode(), response.RawBytes);
var respHeaders = new Dictionary<string, object> { };
foreach (var item in response.Headers)
respHeaders.Add(item.Name, item.Value);
res.SetHeaders(respHeaders);
return res;
}
19
Source : EventHandlerExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static void RaiseEvent<TEventArgs>([MaybeNull] this EventHandler<TEventArgs> @this, object sender) where TEventArgs : EventArgs
{
@this?.Invoke(sender, Activator.CreateInstance<TEventArgs>());
}
19
Source : InlineFormatter.cs
with MIT License
from Alprog
with MIT License
from Alprog
public T Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
{
object instance = InlineFormatter.CallInlineGetter();
if (MessagePackBinary.IsNil(bytes, offset))
{
readSize = 1;
}
else
{
if (instance == null)
{
instance = Activator.CreateInstance<T>();
}
DarkMeta<T>.Value.ReadMembers(Serializer.Instance.State.Settings.Flags, ref instance, bytes, offset, formatterResolver, out readSize, false);
DarkMeta<T>.Value.OnDeserialized(instance);
}
return (T)instance;
}
19
Source : StructFormatter.cs
with MIT License
from Alprog
with MIT License
from Alprog
public T Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
{
object instance = Activator.CreateInstance<T>();
DarkMeta<T>.Value.ReadMembers(Serializer.Instance.State.Settings.Flags, ref instance, bytes, offset, formatterResolver, out readSize, false);
return (T)instance;
}
19
Source : IEnumerableExtensions.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
public static ICollection<T> GetCollection<T>(this IEnumerable<T> data)
{
ICollection<T> internalColl = Activator.CreateInstance<ICollection<T>>();
foreach (T value in data)
{
//if (predicate(value)) yield return value;
internalColl.Add(value);
}
return internalColl;
}
19
Source : JsonHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static T ParseFormByJson<T>(string jsonStr)
{
T obj = Activator.CreateInstance<T>();
using (System.IO.MemoryStream ms =
new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
19
Source : AMActorRpcHandler.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
public async ETTask Handle(Enreplacedy enreplacedy, object actorMessage, Action<IActorResponse> reply)
{
try
{
Request request = actorMessage as Request;
if (request == null)
{
Log.Error($"消息类型转换错误: {actorMessage.GetType().FullName} to {typeof (Request).Name}");
return;
}
E ee = enreplacedy as E;
if (ee == null)
{
Log.Error($"Actor类型转换错误: {enreplacedy.GetType().Name} to {typeof (E).Name} --{typeof (Request).Name}");
return;
}
int rpcId = request.RpcId;
Response response = Activator.CreateInstance<Response>();
void Reply()
{
response.RpcId = rpcId;
reply.Invoke(response);
}
try
{
await this.Run(ee, request, response, Reply);
}
catch (Exception exception)
{
Log.Error(exception);
response.Error = ErrorCode.ERR_RpcFail;
response.Message = exception.ToString();
Reply();
}
}
catch (Exception e)
{
throw new Exception($"解释消息失败: {actorMessage.GetType().FullName}", e);
}
}
19
Source : AMRpcHandler.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
private async ETVoid HandleAsync(Session session, object message)
{
try
{
Request request = message as Request;
if (request == null)
{
Log.Error($"消息类型转换错误: {message.GetType().Name} to {typeof (Request).Name}");
}
int rpcId = request.RpcId;
long instanceId = session.InstanceId;
Response response = Activator.CreateInstance<Response>();
void Reply()
{
// 等回调回来,session可以已经断开了,所以需要判断session InstanceId是否一样
if (session.InstanceId != instanceId)
{
return;
}
response.RpcId = rpcId;
session.Reply(response);
}
try
{
await this.Run(session, request, response, Reply);
}
catch (Exception exception)
{
Log.Error(exception);
response.Error = ErrorCode.ERR_RpcFail;
response.Message = exception.ToString();
Reply();
}
}
catch (Exception e)
{
throw new Exception($"解释消息失败: {message.GetType().FullName}", e);
}
}
19
Source : ObjectPool.cs
with Apache License 2.0
from anpShawn
with Apache License 2.0
from anpShawn
private T CreateClreplacedObject()
{
return (T)Activator.CreateInstance<T>();
}
19
Source : TestComponent.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static T CreateComponent<T>(IWebDriver driver, IWebElement container = null) where T : ITestComponent
{
var component = Activator.CreateInstance<T>();
component.Init(driver, container);
component.Sync(true);
return component;
}
19
Source : IBinaryMapping.cs
with Apache License 2.0
from AntonioDePau
with Apache License 2.0
from AntonioDePau
public static T ReadObject<T>(this IBinaryMapping binaryMapping, Stream stream, int baseOffset = 0)
where T : clreplaced =>
(T)binaryMapping.ReadObject(stream, Activator.CreateInstance<T>(), baseOffset);
19
Source : DatabaseOperation.cs
with MIT License
from ap0405140
with MIT License
from ap0405140
public List<T> Query<T>(string sTsql, bool closeconnect = true)
{
DataTable dt;
List<T> ls;
T tt;
object tt2;
PropertyInfo[] props;
FieldInfo fieldinfo;
DataColumn[] dtcolumns;
ColumnAttribute[] columnattributes;
string targettype, columnname;
int i;
try
{
dt = Query(sTsql, closeconnect);
dtcolumns = dt.Columns.Cast<DataColumn>().ToArray();
ls = new List<T>();
targettype = "";
if (typeof(T).IsValueType
|| typeof(T).Name.ToLower().Contains("string"))
{
targettype = "ValueType";
}
if (typeof(T).Name.StartsWith("ValueTuple"))
{
targettype = "ValueTuple";
}
if (typeof(T).GetConstructors().Any(p => p.GetParameters().Length == 0))
{
targettype = "Clreplaced";
}
foreach (DataRow dr in dt.Rows)
{
switch (targettype)
{
case "ValueType":
tt = (dr[0] == DBNull.Value ? default(T) : (T)dr[0]);
ls.Add(tt);
break;
case "ValueTuple":
tt = Activator.CreateInstance<T>();
tt2 = tt;
for (i = 0; i <= dtcolumns.Length - 1; i++)
{
fieldinfo = tt2.GetType().GetField("Item" + (i + 1).ToString());
if (fieldinfo != null)
{
fieldinfo.SetValue(tt2, (dr[i] == DBNull.Value ? null : dr[i].ToSpecifiedType(fieldinfo.FieldType)));
}
}
tt = (T)tt2;
ls.Add(tt);
break;
case "Clreplaced":
tt = (T)Activator.CreateInstance(typeof(T));
props = typeof(T).GetProperties();
foreach (PropertyInfo prop in props)
{
columnattributes = prop.GetCustomAttributes(typeof(ColumnAttribute), false).Cast<ColumnAttribute>().ToArray();
columnname = (columnattributes.Length > 0 && string.IsNullOrEmpty(columnattributes[0].Name) == false
?
columnattributes[0].Name
:
prop.Name);
if (dtcolumns.Any(c => c.ColumnName == columnname))
{
prop.SetValue(tt, (dr[columnname] == DBNull.Value ? null : dr[columnname]));
}
}
ls.Add(tt);
break;
default:
break;
}
}
return ls;
}
catch (Exception ex)
{
throw new Exception("Run SQL: \r\n" + sTsql
+ "\r\n\r\n" + "ExceptionSource: " + ex.Source
+ "\r\n\r\n" + "ExceptionMessage: " + ex.Message);
}
finally
{
//if (closeconnect == true)
//{
// if (scn.State == ConnectionState.Open)
// {
// scn.Close();
// }
// scn.Dispose();
//}
}
}
19
Source : FakeServer.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken)
{
var prop = typeof(TContext).GetProperty("HttpContext");
_process = (HttpContext ctx) =>
{
var ccc = Activator.CreateInstance<TContext>();
prop.SetValue(ccc, ctx);
return application.ProcessRequestAsync(ccc);
};
return Task.CompletedTask;
}
19
Source : Contract.cs
with MIT License
from armutcom
with MIT License
from armutcom
[replacedertionMethod]
public static void Requires<TException>([replacedertionCondition(replacedertionConditionType.IS_TRUE)]bool condition) where TException : Exception
{
if (condition)
{
return;
}
var exception = Activator.CreateInstance<TException>();
throw exception;
}
19
Source : ComponentsRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponentType CreateComponentWithParent<TComponentType>(FindStrategy by, WindowsElement parenTComponent, WindowsElement foundElement, int elementsIndex)
where TComponentType : Component
{
DetermineComponentAttributes(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponentType>();
element.By = by;
element.ParentWrappedElement = parenTComponent;
element.WrappedElement = foundElement;
element.FoundWrappedElement = foundElement;
element.ElementIndex = elementsIndex;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = pageName ?? string.Empty;
return element;
}
19
Source : ComponentsRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponentType CreateComponentThatIsFound<TComponentType>(FindStrategy by, WindowsElement webElement)
where TComponentType : Component
{
DetermineComponentAttributes(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponentType>();
element.By = by;
element.WrappedElement = webElement;
element.FoundWrappedElement = webElement;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = pageName ?? string.Empty;
return element;
}
19
Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponent CreateComponentWithParent<TComponent, TBy, TDriver, TDriverElement>(TBy by, TDriverElement webElement)
where TComponent : Component<TDriver, TDriverElement>
where TBy : FindStrategy<TDriver, TDriverElement>
where TDriver : AppiumDriver<TDriverElement>
where TDriverElement : AppiumWebElement
{
DetermineComponentAttributes<TDriver, TDriverElement>(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponent>();
element.By = by;
element.ParentWrappedElement = webElement;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = string.IsNullOrEmpty(pageName) ? string.Empty : pageName;
return element;
}
19
Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponent CreateComponentThatIsFound<TComponent, TBy, TDriver, TDriverElement>(TBy by, TDriverElement webElement)
where TComponent : Component<TDriver, TDriverElement>
where TBy : FindStrategy<TDriver, TDriverElement>
where TDriver : AppiumDriver<TDriverElement>
where TDriverElement : AppiumWebElement
{
DetermineComponentAttributes<TDriver, TDriverElement>(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponent>();
element.By = by;
element.FoundWrappedElement = webElement;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = string.IsNullOrEmpty(pageName) ? string.Empty : pageName;
return element;
}
19
Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponentType CreateComponentWithParent<TComponentType>(FindStrategy by, IWebElement parenTComponent, IWebElement foundElement, int elementsIndex, bool shouldCacheElement)
where TComponentType : Component
{
DetermineComponentAttributes(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponentType>();
element.By = by;
element.ParentWrappedElement = parenTComponent;
element.WrappedElement = foundElement;
element.ElementIndex = elementsIndex;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = pageName ?? string.Empty;
element.ShouldCacheElement = shouldCacheElement;
return element;
}
19
Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TComponentType CreateComponentThatIsFound<TComponentType>(FindStrategy by, IWebElement webElement, bool shouldCacheElement)
where TComponentType : Component
{
DetermineComponentAttributes(out var elementName, out var pageName);
var element = Activator.CreateInstance<TComponentType>();
element.By = by;
element.WrappedElement = webElement;
element.ComponentName = string.IsNullOrEmpty(elementName) ? $"control ({by})" : elementName;
element.PageName = pageName ?? string.Empty;
element.ShouldCacheElement = shouldCacheElement;
return element;
}
19
Source : EntityReflector.cs
with MIT License
from Avanade
with MIT License
from Avanade
public TProperty NewValue() => Activator.CreateInstance<TProperty>();
19
Source : Extention.DataTable.cs
with MIT License
from awesomedotnetcore
with MIT License
from awesomedotnetcore
public static List<T> ToList<T>(this DataTable dt)
{
List<T> list = new List<T>();
//确认参数有效,若无效则返回Null
if (dt == null)
return list;
else if (dt.Rows.Count == 0)
return list;
Dictionary<string, string> dicField = new Dictionary<string, string>();
Dictionary<string, string> dicProperty = new Dictionary<string, string>();
Type type = typeof(T);
//创建字段字典,方便查找字段名
type.GetFields().ForEach(aFiled =>
{
dicField.Add(aFiled.Name.ToLower(), aFiled.Name);
});
//创建属性字典,方便查找属性名
type.GetProperties().ForEach(aProperty =>
{
dicProperty.Add(aProperty.Name.ToLower(), aProperty.Name);
});
for (int i = 0; i < dt.Rows.Count; i++)
{
//创建泛型对象
T _t = Activator.CreateInstance<T>();
for (int j = 0; j < dt.Columns.Count; j++)
{
string memberKey = dt.Columns[j].ColumnName.ToLower();
//字段赋值
if (dicField.ContainsKey(memberKey))
{
FieldInfo theField = type.GetField(dicField[memberKey]);
var dbValue = dt.Rows[i][j];
if (dbValue.GetType() == typeof(DBNull))
dbValue = null;
if (dbValue != null)
{
Type memberType = theField.FieldType;
dbValue = dbValue.ChangeType_ByConvert(memberType);
}
theField.SetValue(_t, dbValue);
}
//属性赋值
if (dicProperty.ContainsKey(memberKey))
{
PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
var dbValue = dt.Rows[i][j];
if (dbValue.GetType() == typeof(DBNull))
dbValue = null;
if (dbValue != null)
{
Type memberType = theProperty.PropertyType;
dbValue = dbValue.ChangeType_ByConvert(memberType);
}
theProperty.SetValue(_t, dbValue);
}
}
list.Add(_t);
}
return list;
}
19
Source : Startup{TApplication}.cs
with MIT License
from AximoGames
with MIT License
from AximoGames
private void UIThreadMain()
{
if (Application == null)
Application = Activator.CreateInstance<TApplication>();
Application.SetConfig(Config);
Application.RunSync();
Environment.Exit(0);
}
19
Source : AYUIApplication.cs
with MIT License
from ay2015
with MIT License
from ay2015
protected override void OnStartup(StartupEventArgs e)
{
if (global!=null)
{
global.Application_Start(e, this);
global.RegisterFonts(GlobalCollection.Fonts);
global.RegisterResourceDictionary(GlobalCollection.ResourceDictionaryCollection);
global.RegisterLanuages(GlobalCollection.Lanuages);
//global.RegisterGlobalFilters(GlobalCollection.Filters);
}
if (IsSingleApplication)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName);
Process nowProcess = null;
foreach (Process process in Processes)
{
if (process.Id != currentProcess.Id)
{
nowProcess = process;
}
}
if (nowProcess == null)
{
global.Application_Run(this);
var model = System.Activator.CreateInstance<T>();
model.Show();
}
else
{
WindowShowHelp.ActiveProcess(nowProcess);
this.Shutdown();
}
}
else
{
global.Application_Run(this);
var model = System.Activator.CreateInstance<T>();
model.Show();
}
base.OnStartup(e);
}
19
Source : ClientTokenRing.cs
with MIT License
from azist
with MIT License
from azist
public TToken GenerateNew<TToken>(int expireInSeconds = 0) where TToken : RingToken
{
var token = Activator.CreateInstance<TToken>();
token.Type = typeof(TToken).Name;
//Guid is all that is used for client-side tokens ignoring token byte strength. The GUid serves as an additional nonce
var guid = Guid.NewGuid().ToNetworkByteOrder();//16 bytes
token.ID = guid.ToWebSafeBase64();
token.IssuedBy = this.IssuerName;
var now = App.TimeSource.UTCNow;
token.IssueUtcTimestamp = now;
token.VersionUtcTimestamp = now;
token.ExpireUtcTimestamp = now.AddSeconds(expireInSeconds > 0 ? expireInSeconds : token.TokenDefaultExpirationSeconds);
return token;
}
19
Source : ServerTokenRingBase.cs
with MIT License
from azist
with MIT License
from azist
public virtual TToken GenerateNew<TToken>(int expireInSeconds = 0) where TToken : RingToken
{
var token = Activator.CreateInstance<TToken>();
token.Type = typeof(TToken).Name;
var len = token.TokenByteStrength;
//1. Guid pad is used as a RNG source based on MAC addr/clock
//https://en.wikipedia.org/w/index.php?replacedle=Universally_unique_identifier&oldid=755882275#Random_UUID_probability_of_duplicates
var guid = Guid.NewGuid();
var guidpad = guid.ToNetworkByteOrder();//16 bytes
//2. Random token body
var rnd = App.SecurityManager.Cryptography.GenerateRandomBytes(len);
//3. Concat GUid pad with key
var btoken = guidpad.AppendToNew(rnd);
token.ID = btoken.ToWebSafeBase64();
token.IssuedBy = this.IssuerName;
var now = App.TimeSource.UTCNow;
token.IssueUtcTimestamp = now;
token.VersionUtcTimestamp = now;
token.ExpireUtcTimestamp = now.AddSeconds(expireInSeconds > 0 ? expireInSeconds : token.TokenDefaultExpirationSeconds);
token.IssueUtcTimestamp = token.VersionUtcTimestamp = App.TimeSource.UTCNow;
token.ExpireUtcTimestamp = token.IssueUtcTimestamp.Value.AddSeconds(token.TokenDefaultExpirationSeconds);
return token;
}
19
Source : CreateItemsProvider.cs
with MIT License
from BAndysc
with MIT License
from BAndysc
private static void AddInternals()
{
entries.Add(new Entry("Folder", ProjectWindowUtil.CreateFolder, () => true, null, 20));
var shaderFolder = AddFolder("Shader", 82);
foreach (var entry in UnityScriptTemplates.Entries)
{
string itemName;
var parent = EnsureByPath(entry.Path, entry.Priority, out itemName);
AddScriptTemplate(itemName, entry.Priority, entry.FileName, entry.TemplatePath, parent);
}
AddInternal(typeof(ShaderVariantCollection), "Shader Variant Collection", 94, "New Shader Variant Collection.shadervariants", () => new ShaderVariantCollection(), shaderFolder);
entries.Add(new Entry("Scene", ProjectWindowUtil.CreateScene, () => true, null, 201, typeof(Scene)));
#if !UNITY_2018_3_OR_NEWER
entries.Add(new Entry("Prefab", ProjectWindowUtil.CreatePrefab, () => true, null, 202));
#endif
var createAudioMixer =
typeof(ProjectWindowUtil).GetMethod("CreateAudioMixer", BindingFlags.NonPublic | BindingFlags.Static);
entries.Add(new Entry("Audio Mixer", () => { createAudioMixer.Invoke(null, null); }, () => true, null, 215, typeof(AudioMixer)));
AddInternal(typeof(Material), "Material", 301, "New Material.mat", () => new Material(Shader.Find("Standard")));
AddInternal(typeof(Flare),"Lens Flare", 303, "New Lens Flare.flare", () => new Flare());
AddInternal(typeof(RenderTexture),"Render Texture", 304, "New Render Texture.renderTexture", () => new RenderTexture(256, 256, 24));
AddInternal(typeof(LightmapParameters),"Lightmap Parameters", 305, "New Lightmap Parameters.giparams", () => new LightmapParameters());
AddInternal(typeof(CustomRenderTexture),"Custom Render Texture", 306, "New Custom Render Texture.replacedet", () => new CustomRenderTexture(256, 256));
// not sure what is exact version
#if UNITY_2018_2_OR_NEWER
AddInternal(typeof(SpriteAtlas),"Sprite Atlas", 351, "New Sprite Atlas.spriteatlas", () => new SpriteAtlas());
#else
AddInternal(typeof(SpriteAtlas),"Sprite Atlas", 351, "New Sprite Atlas.spriteatlas", () => Activator.CreateInstance<SpriteAtlas>());
#endif
var sprites = AddFolder("Sprites", 352);
CreateSpritePolygonType createSprite =
new InternalGetter<CreateSpritePolygonType>(typeof(ProjectWindowUtil), "CreateSpritePolygon").Func;
sprites.Children.Add(new Entry("Square", () => createSprite(0), () => true, sprites, 352, typeof(Sprite)));
sprites.Children.Add(new Entry("Triangle", () => createSprite(3), () => true, sprites, 352, typeof(Sprite)));
sprites.Children.Add(new Entry("Diamond", () => createSprite(4), () => true, sprites, 352, typeof(Sprite)));
sprites.Children.Add(new Entry("Hexagon", () => createSprite(6), () => true, sprites, 352, typeof(Sprite)));
sprites.Children.Add(new Entry("Circle", () => createSprite(128), () => true, sprites, 352, typeof(Sprite)));
sprites.Children.Add(new Entry("Polygon", () => createSprite(7), () => true, sprites, 352, typeof(Sprite)));
AddInternal(typeof(AnimatorController),"Animator Controller", 401, "New Animator Controller.controller", () => new AnimatorController());
AddInternal(typeof(AnimationClip),"Animation", 402, "New Animation.anim", () => new AnimationClip());
AddInternal(typeof(AnimatorOverrideController),"Animator Override Controller", 403, "New Animator Override Controller.overrideController", () => new AnimatorOverrideController());
AddInternal(typeof(AvatarMask),"Avatar Mask", 404, "New Avatar Mask.mask", () => new AvatarMask());
AddInternal(typeof(PhysicMaterial),"Physics Material", 501, "New Physic Material.replacedet", () => new PhysicMaterial());
AddInternal(typeof(PhysicsMaterial2D),"Physics Material 2D", 502, "New Physic Material 2D.replacedet", () => new PhysicsMaterial2D());
AddInternal(typeof(Font),"Custom Font", 602, "New Font.fontsettings", () => new Font());
var legacy = AddFolder("Legacy", 850);
AddInternal(typeof(Cubemap), "Cubemap", 850, "New Cubemap.cubemap", () => new Cubemap(64, TextureFormat.RGBAFloat, true), legacy);
}
See More Examples