從頭學Java17-今天的Kotlin更香嗎

来源:https://www.cnblogs.com/burn-red/archive/2023/07/15/17556437.html
-Advertisement-
Play Games

> 出於各種限制,很多公司依然停留在Java8,部分小伙伴轉向了Kotlin。Kotlin作為靜態編譯語言,提供大量語法糖,而且編譯後的位元組碼跟Java一致。 > > 當時,Java8於2014年發佈,Kotlin於2016年,很多宣稱的語法糖都是對比的Java8。不禁要問,相對今天的Java17, ...


出於各種限制,很多公司依然停留在Java8,部分小伙伴轉向了Kotlin。Kotlin作為靜態編譯語言,提供大量語法糖,而且編譯後的位元組碼跟Java一致。

當時,Java8於2014年發佈,Kotlin於2016年,很多宣稱的語法糖都是對比的Java8。不禁要問,相對今天的Java17,Kotlin優勢還在嗎?

現在就用最新的Kotlin1.9.0,對前三篇文章里的lambda、StreamAPI依次改造,實踐出真知!

編寫lambda、調用

Java

import Java.util.*;
import Java.util.function.*;

/**
 *
 * @author 燒哥burn.red
 */
public class Test1 {
    
    public static void main(String[] args) {
        
        Predicate<String> predicate = s -> s.length() == 3;
        Consumer<String> consumer = s -> System.out.println(s);
        Supplier<String> supplier = () -> "Hello Duke!";
        Function<String, Integer> function = s -> s.length();
        
        IntSupplier intSupplier = () -> 1;
        IntConsumer intConsumer = s -> System.out.println(s);
        IntPredicate intPredicate = i -> i > 10;
        ToIntFunction<String> toIntFunction = s -> s.length();
        UnaryOperator<String> unaryOperator = s -> s.toUpperCase();
        
        BiConsumer<String, Integer> biConsumer = (s, number) -> s.indexOf(number);
        ObjIntConsumer<String> objIntConsumer = (s, value) -> System.out.printf("%s,%d\n", s, value);
        BiPredicate<String, Integer> biPredicate = (word, length) -> word.length() == length;
        BiFunction<String, String, Integer> biFunction = (word, sentence) -> sentence.indexOf(word);
        ToIntBiFunction<String, String> toIntBiFunction = (word, sentence) -> sentence.indexOf(word);
        
        String a = "aaa";
        
        if (predicate.test(a)) {
            consumer.accept(a);
            supplier.get();
            function.apply(a);
            
            intConsumer.accept(1);
            intSupplier.getAsInt();
            intPredicate.test(11);
            toIntFunction.applyAsInt(a);
            unaryOperator.apply(a);
            
            biConsumer.accept(a, 2);
            objIntConsumer.accept(null, 1);
            biPredicate.test(a, 3);
            biFunction.apply("fdsa", a);
            toIntBiFunction.applyAsInt("fdsa", a);
        }
        List<String> strings = new ArrayList<>(List.of("a", "bb", "ccc"));
        strings.forEach(consumer);
        strings.removeIf(predicate);//不應該在不可變集合上調用
        System.out.println(strings);
        
        strings = Arrays.asList("a", "bb", "ccc");
        strings.replaceAll(unaryOperator);
        System.out.println(strings);

//        int i = 0;
//        Consumer<Integer> add = s -> i++;//報錯,從lambda 表達式引用的本地變數必須是最終變數或實際上的最終變數
    }
}

Kotlin

/**
 *
 * @author 燒哥burn.red
 */

fun main() {
    val predicate = { s: String -> s.length == 3 }
    val consumer = { s: String? -> println(s) }
    val supplier = { "Hello Duke!" }
    val function = { s: String -> s.length }

    val intSupplier = { 1 }
    val intConsumer = { s: Int -> println(s) }
    val intPredicate = { i: Int -> i > 10 }
    val toIntFunction = { s: String -> s.length }
    val unaryOperator = { s: String -> s.uppercase() }

    val biConsumer = { s: String, number: Int -> s.indexOf(number.toChar()) }
    val objIntConsumer = { s: String?, value: Int -> println("$s,$value") }
    val biPredicate = { word: String, length: Int -> word.length == length }
    val biFunction = { word: String?, sentence: String -> sentence.indexOf(word!!) }
    val toIntBiFunction = { word: String?, sentence: String -> sentence.indexOf(word!!) }

    val a = "aaa"

    if (predicate(a)) {
        consumer(a)
        supplier()
        function(a)

        intConsumer(1)
        intSupplier()
        intPredicate(11)
        toIntFunction(a)
        unaryOperator(a)

        biConsumer(a, 2)
        objIntConsumer(null, 1)
        biPredicate(a, 3)
        biFunction("fdsa", a)
        toIntBiFunction("fdsa", a)
    }
    var strings = mutableListOf("a", "bb", "ccc")
    strings.forEach(consumer)
    strings.removeIf(predicate) //不應該在不可變集合上調用
    println(strings)

    strings = arrayListOf("a", "bb", "ccc")
    strings.replaceAll(unaryOperator)
    println(strings)

    var i = 0
    val add = { s: Int? -> i++ } //不報錯
    add(i)
    println(i)
}

可以看出:

  • Kotlin的lambda,沒有那四種劃分,調用時類似函數,(參數..),非常簡潔
  • Kotlin的lambda,可以改變外層變數的值
  • Kotlin沒有自己的removeIf,replaceAll,但可以直接調用Java的
  • Java為原始類型準備了特別版,Kotlin預設都是原始類型
  • Kotlin變數預設都是非null

這一局,Kotlin勝出。

方法引用、鏈接

Java

import red.burn.bean.User;

import Java.util.*;
import Java.util.function.*;
import Java.util.logging.Logger;

/**
 * @author 燒哥burn.red
 */
public class Test2 {

    public static void main(String[] args) {
        //方法引用
        DoubleUnaryOperator sqrt = Math::sqrt;
        IntBinaryOperator max = Integer::max;//靜態方法引用
        Supplier<List<String>> newListOfStrings = ArrayList::new;//構造方法引用
        Consumer<String> printer = System.out::println;//綁定到System.out
        Function<String, Integer> toLength = String::length;//非綁定,綁定到String的實例

        //Lambla的鏈接
        Predicate<String> isNull = Objects::isNull;
        Predicate<String> isEmpty = String::isEmpty;
        Predicate<String> isNullOrEmpty = isNull.or(isEmpty);
        Predicate<String> isNotNullNorEmpty = isNullOrEmpty.negate();
        Predicate<String> shorterThan5 = s -> s.length() < 5;
        Predicate<String> p = isNotNullNorEmpty.and(shorterThan5);

        Logger logger = Logger.getLogger("MyApplicationLogger");
        Consumer<String> log = logger::info;
        Consumer<String> printStr = System.out::println;
        Consumer<String> printAndLog = log.andThen(printStr);//
        printAndLog.accept("test");

        Function<String, Integer> function1 = String::length;
        Function<Integer, Integer> function2 = s -> ++s;
        Function<String, Integer> function = function1.andThen(function2);
        System.out.println("new=" + function.apply("abc")); //4

        Function<String, String> id = Function.identity();

        //Comparator
        Comparator<Integer> comparator = Integer::compare;
        Comparator<String> comparator1 = (s1, s2) -> Integer.compare(s1.length(), s2.length());
        Comparator<String> comparator2 = (s1, s2) -> Integer.compare(toLength.apply(s1), toLength.apply(s2));
        Comparator<String> comparator3 = Comparator.comparing(String::length);

        Comparator<User> byFirstName = Comparator.comparing(User::getFirstName);
        Comparator<User> byLastName = Comparator.comparing(User::getLastName);
        Comparator<User> byFirstNameThenLastName = byFirstName.thenComparing(byLastName)
                                                              .thenComparingInt(User::getAge);
        Comparator<User> byFirstNameThenLastName1 = Comparator.comparingInt(User::getAge)
                                                              .thenComparing(
                                                                      Comparator.nullsLast(Comparator.naturalOrder()));

        List<String> strings = Arrays.asList("one", "two", "three", "four", "five");
        strings.sort(comparator3.reversed());
        System.out.println(strings);
    }
}
import lombok.Builder;
import lombok.Data;
import org.jetbrains.annotations.NotNull;

/**
 * @author 燒哥burn.red
 */
@Data
@Builder
public class User implements Comparable<User> {

    private String name;
    private int age;
    private String firstName;
    private String lastName;

    @Override
    public int compareTo(User o) {

        return this.name.compareTo(o.name);
    }
}

Kotlin

import Java.util.logging.Logger
import Kotlin.math.sqrt
import red.burn.bean.UserKT
import Kotlin.math.max

/**
 *
 * @author 燒哥burn.red
 */
fun main() {
    //方法引用
    val sqrt = ::sqrt
//    val max = ::max //報錯,歧義
//    val newListOfStrings = ::ArrayList  //報錯,歧義
//    val printer =::println //報錯,歧義
    val ar = 5.run<Int, ArrayList<String>>(::ArrayList)
    "a".run(::println)
    val kt = ::UserKT //構造方法引用
    val user = kt("abc", 10)
    var (name, age) = UserKT("csc")
    val firstName = user::firstName //屬性引用
    val addAge = user::addAge //函數引用
    val toLength = String::length  //非綁定,綁定到String的實例

    //Lambla的鏈接
    val isNull = { obj: String? -> obj == null }
    val isEmpty = { obj: String -> obj.isEmpty() }
    val isNullOrEmpty = { obj: String? -> obj == null || isEmpty(obj) }
    val isNotNullNorEmpty = { obj: String? -> !isNullOrEmpty(obj) }
    val shorterThan5 = { s: String -> s.length < 5 }
    val p = { s: String -> isNotNullNorEmpty(s).and(shorterThan5(s)) }

    val logger = Logger.getLogger("MyApplicationLogger")
    val log = { message: String? -> logger.info(message) }
    val printStr = { message: String? -> println(message) }
    val printAndLog = { message: String? ->
        log(message).also { printStr(message) }
    }
    printAndLog("test")

    val function1 = String::length
//    val function2 = {  s: Int -> ++s }//報錯 Val cannot be reassigned
    val function2 = { s: Int ->
        var i = s;
        ++i;
    }
    val function = { s: String -> function1(s).let(function2) }
    println("new=" + function("abc")) //4

    val id = { s: String? -> s }

    //Comparator
    val comparator = { x: Int, y: Int -> (x).compareTo(y) }
    val comparator1 = { s1: String, s2: String -> s1.length.compareTo(s2.length) }
    val comparator2 = { s1: String, s2: String -> toLength(s1).compareTo(toLength(s2)) }
    val comparator3 = compareBy(String::length)

    val byFirstName = compareBy(UserKT::firstName)
    val byLastName = compareBy(UserKT::lastName)
    val byFirstNameThenLastName = byFirstName.then(byLastName).thenBy(UserKT::age)
    val byFirstNameThenLastName1 = compareBy(UserKT::age).then(nullsLast(naturalOrder()))

    val strings = arrayListOf("one", "two", "three", "four", "five")
    strings.sortWith(comparator3.reversed())
    println(strings)
}

/**
 *
 * @author 燒哥burn.red
 */
data class UserKT(var name: String, var age: Int = 1) : Comparable<UserKT> {

    var firstName: String? = null
    var lastName: String? = null

    override fun compareTo(other: UserKT): Int {
        return name.compareTo(other.name)
    }

    fun printUser(s: UserKT) {
        println(s)
    }

    fun addAge(i: Int, j: Int): Int {
        return i + j
    }

}

可以看出:

  • Kotlin的lambda,可以有類引用、函數引用、屬性引用、構造引用,其中函數引用不能有歧義
  • Kotlin的lambda,因為沒有四種劃分,缺乏Java里豐富的鏈接方式,不過可以自己實現
  • Kotlin的lambda,無法修改自己的參數,只能讀取
  • Kotlin可讀性比較強,Java容易看的分神

這一局,Kotlin跟Java打平。

StreamAPI

Java

import Java.util.List;
import Java.util.Map;
import Java.util.function.*;
import Java.util.stream.*;

/**
 * @author 燒哥burn.red
 */
public class Test3 {
    
    public static void main(String[] args) {
        
        //flatmap
        Function<String, Stream<Integer>> flatParser = s -> {
            try {
                return Stream.of(Integer.parseInt(s));
            } catch (NumberFormatException e) {
            }
            return Stream.empty();
        };
        
        List<String> strings = List.of("1", " ", "2", "3 ", "", "3");
        List<Integer> ints = strings.stream().flatMap(flatParser).toList();
        System.out.println("ints = " + ints);
        
        //mapMulti
        ints = strings.stream().<Integer>mapMulti((string, consumer) -> {
            try {
                consumer.accept(Integer.parseInt(string));
            } catch (NumberFormatException ignored) {
            }
        }).toList();
        System.out.println("ints = " + ints);
        
        List<Integer> ints2 = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
        List<Integer> result = ints2.stream().skip(2).limit(5).toList();
        System.out.println("result = " + result);
        
        List<Integer> list0 = List.of(1, 2, 3);
        List<Integer> list1 = List.of(4, 5, 6);
        List<Integer> list2 = List.of(7, 8, 9);
// 1st pattern: concat
        List<Integer> concat = Stream.concat(list0.stream(), list1.stream()).toList();
// 2nd pattern: flatMap
        List<Integer> flatMap = Stream.of(list0.stream(), list1.stream(), list2.stream())//類似city的外層組成的流
                                      .flatMap(Function.identity()).toList();
        System.out.println("concat  = " + concat);
        System.out.println("flatMap = " + flatMap);
        
        //reduce
        Stream<String> strings1 = Stream.of("one", "two", "three", "four");
        BinaryOperator<Integer> combiner = Integer::sum;
        Function<String, Integer> mapper = String::length;
        BiFunction<Integer, String, Integer> accumulator = (partialReduction, element) -> partialReduction + mapper.apply(element);
        int result1 = strings1.reduce(0, accumulator, combiner);
        System.out.println("sum = " + result1);
        
        //groupby map
        List<String> strings2 = List.of("two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve");
        Map<Integer, Long> histogram = strings2.stream().collect(Collectors.groupingBy(String::length, Collectors.counting()));
        histogram.forEach((k, v) -> System.out.println(k + " :: " + v));
        
        Map<Long, List<Integer>> map = histogram.entrySet()
                                                .stream()
                                                .collect(Collectors.groupingBy(Map.Entry::getValue,
                                                                               Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
        Map.Entry<Long, List<Integer>> result2 = map.entrySet().stream().max(Map.Entry.comparingByKey())//再求max
                                                    .orElseThrow();
        System.out.println("result = " + result2);
    }
}

Kotlin

/**
 * @author 燒哥burn.red
 */
fun main() {
    
    //flatmap
    val flatParser = label@{ s: String ->
        try {
            return@label listOf(s.toInt())
        } catch (_: NumberFormatException) {
        }
        emptyList<Int>()
    }

    val strings = listOf("1", " ", "2", "3 ", "", "3")
    var ints = strings.flatMap(flatParser)
    println("ints = $ints")

    //mapMulti
    /*ints = strings.mapMulti { string: String, consumer: Consumer<Int?> ->
            try {
                consumer.accept(string.toInt())
            } catch (ignored: NumberFormatException) {
            }
        }
    println("ints = $ints")*/

    val ints2 = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
    val result = ints2.drop(2).take(5)
    println("result = $result")

    val list0 = listOf(1, 2, 3)
    val list1 = listOf(4, 5, 6)
    val list2 = listOf(7, 8, 9)
// 1st pattern: concat
    val concat = list0 + list1
// 2nd pattern: flatMap
    val flatMap = listOf(list0, list1, list2).flatten()
    println("concat  = $concat")
    println("flatMap = $flatMap")

    //reduce
    val strings1 = listOf("one", "two", "three", "four")
    val mapper = String::length
    val accumulator = { partialReduction: Int, element: String -> partialReduction + mapper(element) }
    val result1 = strings1.fold(0, accumulator)
    println("sum = $result1")

     //groupby map
    val strings2 = listOf("two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve")
    val histogram: Map<Int, Int> = strings2.groupingBy { it.length }.eachCount()
    histogram.forEach({ k, v -> println("$k :: $v") })

    val map = histogram.map { it }.groupBy({ it.value }, { it.key }).maxBy { it.key }
    println(map)

}

可以看出:

  • Kotlin的lambda,不支持multiMap,但可以自己實現
  • Kotlin有運算符重載,可以對集合進行+-
  • flatten簡化了flatmap,fold簡化了reduce,eachCount簡化了分組計數
  • 集合直接就是流,集合上的groupby等直接調用,不需要collect()
  • 函數很多有混淆,像groupBygroupingBymaxBymaxOf
  • 不過中間可能有null,還需要人工判斷,不如Java,Optional總不會報錯
  • groupBy({ it.value }, { it.key }).maxBy { it.key }這個能亮瞎

總體來說,代碼量減少非常多,這局Kotlin勝出。

綜合

Java

import red.burn.bean.*;

import Java.util.*;
import Java.util.function.BiFunction;
import Java.util.function.Function;
import Java.util.stream.*;

/**
 *
 * @author 燒哥burn.red
 */
public class Test4 {
    
    public static void main(String[] args) {
        
        Author au1 = new Author("Au1");
        Author au2 = new Author("Au2");
        Author au3 = new Author("Au3");
        Author au4 = new Author("Au4");
        Author au5 = new Author("Au5");
        Article a1 = new Article("a1", 1991, List.of(au1));
        Article a2 = new Article("a2", 1992, List.of(au1, au2));
        Article a3 = new Article("a3", 1993, List.of(au1, au3, au4));
        Article a4 = new Article("a4", 1992, List.of(au1, au2, au3, au4));
        List<Article> articles = List.of(a1, a2, a3, a4);
        
        BiFunction<Article, Author, Stream<PairOfAuthors>> buildPairOfAuthors =
                (article, firstAuthor) -> article.authors().stream().flatMap(
                        secondAuthor -> PairOfAuthors.of(firstAuthor, secondAuthor).stream());//Optional的Stream
        
        Function<Article, Stream<PairOfAuthors>> toPairOfAuthors =
                article -> article.authors().stream().flatMap(firstAuthor -> buildPairOfAuthors.apply(article, firstAuthor));
        Collector<PairOfAuthors, ?, Map<PairOfAuthors, Long>> collector1 =
                Collectors.groupingBy(Function.identity(), Collectors.counting());

//        System.out.println("numberOfAuthorsTogether=" + numberOfAuthorsTogether);
        Function<Map<PairOfAuthors, Long>, Map.Entry<PairOfAuthors, Long>> finisher1 =
                map1 -> map1.entrySet().stream().max(Map.Entry.comparingByValue()).orElseThrow();
        
        Map.Entry<PairOfAuthors, Long> result11 =
                articles.stream().flatMap(toPairOfAuthors).collect(Collectors.collectingAndThen(collector1, finisher1));
        
        Map.Entry<PairOfAuthors, Long> result12 =
                articles.stream().collect(Collectors.flatMapping(toPairOfAuthors, Collectors.collectingAndThen(collector1, finisher1)));
        
        //找出每年發表文章最多的兩位聯合作者
        Collector<Article, ?, Optional<Map.Entry<PairOfAuthors, Long>>> flatMapping = Collectors.flatMapping(toPairOfAuthors,
                                                                                                             Collectors.collectingAndThen(
                                                                                                                     collector1,
                                                                                                                     map2 -> map2.entrySet()
                                                                                                                                 .stream()
                                                                                                                                 .max(Map.Entry.comparingByValue())));
        Map<Integer, Optional<Map.Entry<PairOfAuthors, Long>>> result13 =
                articles.stream().collect(Collectors.groupingBy(Article::inceptionYear, flatMapping));
        Map<Integer, Map.Entry<PairOfAuthors, Long>> result14 = result13.entrySet()
                                                                        .stream()
                                                                        .flatMap(entry -> entry.getValue()
                                                                                               .map(value -> Map.entry(entry.getKey(),
                                                                                                                       value))
                                                                                               .stream())
                                                                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        
        System.out.println(result11);
        System.out.println(result12);
        System.out.println(result13);
        System.out.println(result14);
    }
}
public record Article(String title, int inceptionYear, List<Author> authors) {

}
public record Author(String name) implements Comparable<Author> {
    
    public int compareTo(Author other) {
        
        return this.name.compareTo(other.name);
    }
}

public record PairOfAuthors(Author first, Author second) {
    
    public static Optional<PairOfAuthors> of(Author first, Author second) {
        
        if (first.compareTo(second) > 0) {
            return Optional.of(new PairOfAuthors(first, second));
        } else {
            return Optional.empty();
        }
    }
}

Kotlin


可以看出:

  • 這個例子主要體現Optional跟StreamAPI的結合,Kotlin里沒有Optional,所以很難寫出。

這局Java勝。

最終

Kotlin以2:1微弱優勢勝出。

Java用他的嚴謹,證明能實現從簡單到複雜的各種場景。

Kotlin用它的簡潔,通常情況下能減少工作量。

Kotlin還提供了委托、擴展、運算符重載、作用域函數、協程等等。

子曾經曰過”越簡潔,越有坑“。想完全用Kotlin取代Java,還有一段路,目前二者可以互操作,建議同時使用。

複雜場景下,用什麼語言並不是決定性的,解決方案才是。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ### 概述 BOM(Browser Object Model)瀏覽器對象模型,就是操作瀏覽器的一些能力,可以操作的內容如下: - 獲取一些瀏覽器相關信息(視窗大小) - 操作瀏覽器的滾動條 - 瀏覽器的信息(瀏覽器的版本) - 讓瀏覽器出現一個彈窗(alert,confirm,prompt) BO ...
  • 新建axiosj.ts import axios from 'axios'; import { showMessage } from "./status"; // 引入狀態碼文件 import { ElMessage } from 'element-plus' // 引入el 提示框,這個項目里用什 ...
  • TLDR vscode的GraphQL語法插件, 目前比較推薦Graphql Foundation的GraphQL: Language Feature Support 相關配置, 見[GraphQL: Language Feature Support](# GraphQL: Language Fea ...
  • ![](https://img2023.cnblogs.com/blog/3076680/202307/3076680-20230713135333820-1976638091.png) # 1. 互連層是可以真正構建高可用性的地方 ## 1.1. 流量管理 ## 1.2. 負載均衡 ## 1.3. ...
  • 1、導入 關於Win32的錯誤認知: (1)已經有malloc()函數了,為什麼還要學Win32 API? (2)學MFC就可以了,為什麼要學Win32? Win32課程包含的內容: 01、字元 09、文件系統 02、多線程 10、記憶體映射 03、線程同步 11、DLL 04、視窗的本質 12、遠程 ...
  • 一、jupyter notebook介紹 1、簡介 Jupyter Notebook是基於網頁的用於交互計算的應用程式。其可被應用於全過程計算:開發、文檔編寫、運行代碼和展示結果。——Jupyter Notebook官方介紹 簡而言之,Jupyter Notebook是以網頁的形式打開,可以在網頁頁 ...
  • # java操作zookeeper 1. 創建一個maven項目在pom文件里引入如下依賴: ~~~XML junit junit 4.10 test org.apache.curator curator-framework 4.0.0 org.apache.curator curator-reci ...
  • # 尾碼數組是什麼 尾碼數組就是主要處理字元串尾碼問題的,它的實現演算法主要有兩種:倍增法和 DC3,複雜度分別是 $O(n\log n)$ 和 $O(n)$。這裡由於 DC3 代碼答辯且難以理解,我就只寫了倍增法的實現。 # 例題引入 [P3809 【模板】尾碼排序](https://www.luo ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...