-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathActivatorExtensions.cs
More file actions
53 lines (48 loc) · 1.55 KB
/
ActivatorExtensions.cs
File metadata and controls
53 lines (48 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using BootstrapBlazor.Socket.Logging;
using System.Reflection;
namespace System;
/// <summary>
/// Activator 扩展方法
/// </summary>
public static class ActivatorExtensions
{
/// <summary>
/// 通过指定类型与参数创建实例方法
/// </summary>
/// <param name="type"></param>
/// <param name="args"></param>
/// <returns></returns>
public static object? CreateInstance(this Type type, object?[]? args = null)
{
var bindings = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
object? instance = null;
try
{
instance = Activator.CreateInstance(type, bindings, null, args, null);
}
catch (Exception ex)
{
SocketLogging.LogError(ex, $"Create Instance {type.FullName} failed");
}
return instance;
}
/// <summary>
/// 通过指定类型与参数创建实例方法
/// </summary>
/// <param name="type"></param>
/// <param name="args"></param>
/// <returns></returns>
public static TType? CreateInstance<TType>(this Type type, object?[]? args = null)
{
TType? ret = default;
var value = type.CreateInstance(args);
if (value is TType v)
{
ret = v;
}
return ret;
}
}