C#如何使用Java Enum

C#如何使用Java Enum

因C#與Java語言特性不同的關係,在enum的使用上有很大的不同。
這邊提供方法相同,但寫法不同的範例提供參考。

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
54
Java Enum example:

package com.commons.type;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.manager.ApacheHttpClientManager;
import com.util.LogUtils;

public enum TelegramBotType {

Example("token_example", "chatid_example");

private String token;

private String chatId;

private String messageUrl;

TelegramBotType(String token, String chatId) {
this.token = token;
this.chatId = chatId;
this.messageUrl = "https://api.telegram.org/bot" + token + "/sendMessage";
}

public void sendMessage(String msg, boolean isHTML) {
// 如果沒有設定,改由log4j紀錄
if (this.chatId == null || this.token == null || this.messageUrl == null) {
LogUtils.telegramBot.info("Telegram " + this.name() + " : " + msg);
return;
}

try {
ApacheHttpClientManager.HttpPostRequest httpPostRequest = ApacheHttpClientManager.getInstance()
.getHttpPostRequest(this.messageUrl);

Map<String, String> postParam = new HashMap<>();
postParam.put("chat_id", chatId);
postParam.put("text", msg);
if (isHTML) {
postParam.put("parse_mode", "HTML");
}
httpPostRequest.setParameters(postParam);
ApacheHttpClientManager.getInstance().execute(httpPostRequest);
} catch (Exception e) {
LogUtils.telegramBot.error("failure message transmission msg:" + msg + ", isHTML:" + isHTML, e);
}
}
}
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
C# Enum example:

using Example.Source.Net.com.util;
using System;
using System.Collections.Specialized;

namespace Example.Source.Net.com.commons.type
{
public sealed class TelegramBotType
{
private readonly string token;
private readonly string chatId;
private readonly string messageUrl;

public static readonly TelegramBotType Example = new TelegramBotType("token_example", "chatid_example");

private TelegramBotType(string token, string chatId)
{
this.token = token;
this.chatId = chatId;
messageUrl = "https://api.telegram.org/bot" + token + "/sendMessage";
}

public void sendMessage(string msg, int timeout)
{
// 如果沒有設定,改由log4j紀錄
if (chatId == null || token == null || messageUrl == null)
{
LogUtil.logger.Warn("No Telegram Setting : " + msg);
return;
}

try
{
var values = new NameValueCollection
{
{"chat_id", chatId},
{"text", msg}
};
ApiServiceUtil.POST(messageUrl, values, timeout);
}
catch (Exception e)
{
LogUtil.logger.Error("failure message transmission msg:" + msg + ";" + Convert.ToString(e));
}
}
}
}